One of my friend recently asked me a question that I think I should share with you. Say you have a Static Implementation of a Type T which you pass as Open Type in your Generic Class. Now the problem is how to get reference to the Static Members or invoke a method that is Static to the Type from the Open Type T. In this post, I will demonstrate few implementations that help you getting the Static implementation.
First of all, According to C# documentation, any type allocates its static members once per Type rather than once per Open Type. Now lets define this using the code below :
Handy Tricks and Tips to do your .NET code Fast, Efficient and Simple. Some common questions that comes into mind. Please check if you could find them listed or not.
Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts
Friday, October 7, 2011
Thursday, September 1, 2011
31 Tips for the month on Threading, WPF, MEF, ASP.NET
Daily .NET Tips is aiming to sharing useful coding tips and tricks for .NET Developers. This site completely design for sharing Tips and Tricks, useful Code Snippet which anyone use in daily development work and targeted anything related with .NET. This month we have wide range of tips including Threading, MEF, WPF and MVC. In this post I am quickly listing down all the tips which are published over the month August 2011. And the most important point to mention, among those 31 tips that has been posted on DailyDotnettips this month 22 is coming from me.
- Working with AggregateCatalog in MEF
- Working with DirectoryCatalog in MEF
- Working with AssemblyCatalog in MEF
- Working with TypeCatalog in MEF
- How to use DebuggerTypeProxy while debugging your sensitive Type
- ASP.NET Calendar Control as Outlook Calendar
- Initialize assemblies using PreApplicationStartMethod for ASP.NET 4.0 Application
- Async Lambda Expression
- Playing with ASP.NET List Controls using jQuery
- How to allow user to input html in ASP.NET MVC?
- Using Mutex to avoid deadlocks
- Writing inline Code in WPF
- What is SynchronizationContext all about
- ThreadLocal storage in .NET
- Barrier in .NET 4.0
- Use of Interlocked in Race Condition
- Call ASP.NET Page Methods using your own AJAX
- Use of SpinLock for ThreadLocking
- Using ReaderWriterLock over Monitor for Thread Locking
- What is the use of IsBackground property of Thread?
- Enable Address Level Debugging in Visual Studio
- Get List of all Control Types in WPF
- How to apply simple faded transparent effects on WPF controls ?
- Use Visual Studio Server Explorer to Add New or Existing SQL Server CE Database
- Co-Ordinated Thread Shutdown with and without using CancellationTokenSource
- Generate thousand of request
- Writing a Stretchable ContentControl in WPF
- How to Retrieve WPF Visual Tree Programmatically ?
- What is Visual Tree and Logical Tree in WPF?
- Dealing with HWND in WPF
- Hosting a WPF control inside a Windows Form
To get regular updates visit http://dailydotnettips.com and follow @dailydotnettips at Twitter.
I hope you would like the posts. Stay tune for more.
Labels:
.NET 4.0,
architecture,
ASP.NET 4.0,
C#,
MEF,
Patterns,
Reflection,
Threading,
tips,
WPF,
XAML
Sunday, July 3, 2011
Rethinking my Session on TechEd on Road
Hi Folks,
Its been a great time together on TechEd on Road event here in Kolkata. I can recollect the fun we had out of the sessions with Pinal Dave, nice to find you here Pinal and with Bijoy Singhal on Windows Phone 7. I would also like to thank Dhanajay Kumar for coming all the way from Pune only for this session, and also for giving a wonderful session to us.
Lets now talk about my session on ".NET Fundamentals that every developers should Know". In this post I will share all the resources and source codes to make your easy way round to understand everything that you didnt understand in the session, of course if any... :)
Labels:
.NET 4.0,
architecture,
C#,
DLR,
MEF,
Online Session,
Reflection
Saturday, June 4, 2011
Playing with Reflection and Async
Hi Guys,
In this code I have just put a delay of 10 seconds. Now after the execution is finished, another message will be printed on the screen.
Task Asynchronous Pattern as you already know from my article, is one of the major change of next generation .NET applications. As this is already discussed in detail in the article, I will not repeat the same again here in this post. If you don't know what is it, please go ahead and read the article. In this post, I will try to use reflection to invoke our own async method.
So to start, let us take a look at one of the simplest Async method.
static void Main(string[] args) { Program p = new Program(); Task t = p.TryCallAsync(10000); t.Wait(); Console.ReadLine(); } public async Task TryCallAsync(int delay) { Console.WriteLine("TaskEx.Delay is called : will wait for {0} milliseconds", delay); await TaskEx.Delay(delay); Console.WriteLine("Finished execution Return to the caller"); }
In this code I have just put a delay of 10 seconds. Now after the execution is finished, another message will be printed on the screen.
Labels:
async,
C#,
C#5.0,
CodeProject,
DLR,
internals,
Reflection
Saturday, November 6, 2010
Reflection - Slow or Fast? Demonstration with Solutions
Many of you might have heard, calling reflection APIs from your code is always slower than that of calling it directly. Well, it is right. Some of the major Reflection methods like GetXXX (of MethodInfo, PropertyInfo, FieldInfo etc) are say 100 times slower than that of calling a Method, Property or Fields directly. In this post, I will try to cover some of the major portion of Reflection which is slower like hell than that of normal method call and also try to solve the same.
So what is Reflection for?
As I have already told you about Reflection and Code Emit and also how to build your Lamda Expression Tree, it is good to know where you would like to use Reflection. Yes... Reflection is made truly late bound approach to browse through the object hierarchy or to call methods inside the object. So if you do not know much about your object hierarchy or you have somehow found an assembly external to your application and you need to parse through the object and call its methods say, then Reflection would be the right choice for you.
So basically Reflection allows you to create plugin type of applications where you define an Interface and publish the same for your application and let others create those plugins for you to seamlessly added to your application. Fine. Then what it isn't for?
Yes basically few people try to work everything based on Reflection. Using reflection unnecessarily will let your application very costly. Say for instance,
Or say using
Silly huh..
I saw few people to do this. They try to use everything using Reflection, may be they love the Reflection too much, or they have already created a Reflection engine right and do not want to mix up unknown types with known ones. May be they would make their code clear by calling the known types to the same module that is built up for dealing with unknown types.
Download Sample - 60 KB
So what is Reflection for?
As I have already told you about Reflection and Code Emit and also how to build your Lamda Expression Tree, it is good to know where you would like to use Reflection. Yes... Reflection is made truly late bound approach to browse through the object hierarchy or to call methods inside the object. So if you do not know much about your object hierarchy or you have somehow found an assembly external to your application and you need to parse through the object and call its methods say, then Reflection would be the right choice for you.
So basically Reflection allows you to create plugin type of applications where you define an Interface and publish the same for your application and let others create those plugins for you to seamlessly added to your application. Fine. Then what it isn't for?
Yes basically few people try to work everything based on Reflection. Using reflection unnecessarily will let your application very costly. Say for instance,
ConstructorInfo cinfo= typeof(MyType).GetConstructor(new Type[] { typeof(int), typeof(string) }); object createdObject = cinfo.Invoke(new object[] { 10, "Abhishek" }); MyType xyz = createdObject as MyType;
Or say using
MyType typ = Activator.CreateInstance<MyType>();
Silly huh..
I saw few people to do this. They try to use everything using Reflection, may be they love the Reflection too much, or they have already created a Reflection engine right and do not want to mix up unknown types with known ones. May be they would make their code clear by calling the known types to the same module that is built up for dealing with unknown types.
Download Sample - 60 KB
Labels:
.NET,
.NET 3.5,
.NET 4.0,
.NET Memory Management,
C#,
Reflection
Sunday, October 24, 2010
DLR using Reflection.Emit (In Depth) Part 2
In my previous post, I was discussing how you could create your own assembly at runtime or rather how you could compile an assembly type dynamically using Reflection.Emit. In this post I will take it further by giving away a number of examples for your better understanding how to build your own custom types dynamically during runtime. I will also try to cover up a portion of MSIL concepts so that you could unleash the power of MSIL easily in your application.
The Basics
To build a dynamic type, the most important thing that we have discussed already are Builder classes. The BCL exposes a number of Builder classes that enables us to generate MSIL code dynamically during runtime and hence you can compile the same to produce the output.
From the above figure I have put some of the most important Builder classes marked in Red. But ultimately, you need instructions to run for your application. To write your IL Expression, Reflection.Emit provides a class call ILGenerator. ILGenerator (marked in blue) enables you to write your IL for a method or property. OpCodes are Operation code that determined Computer instructions. So while writing your instructions you need to pass your OpCodes and generate the instruction set for the Method.
Now going further with our example, let me demonstrate the code one by one so that you could easily build your own Code generator.
Implement IBuilder for your Assembly
Lets move to the actual implementation of IBuilder interface. As per our discussion, IBuilder contains 4 members, Sum, Divide, Multiply & substract.
Download Sample Application - 66 KB
The Basics
To build a dynamic type, the most important thing that we have discussed already are Builder classes. The BCL exposes a number of Builder classes that enables us to generate MSIL code dynamically during runtime and hence you can compile the same to produce the output.
From the above figure I have put some of the most important Builder classes marked in Red. But ultimately, you need instructions to run for your application. To write your IL Expression, Reflection.Emit provides a class call ILGenerator. ILGenerator (marked in blue) enables you to write your IL for a method or property. OpCodes are Operation code that determined Computer instructions. So while writing your instructions you need to pass your OpCodes and generate the instruction set for the Method.
Now going further with our example, let me demonstrate the code one by one so that you could easily build your own Code generator.
Implement IBuilder for your Assembly
Lets move to the actual implementation of IBuilder interface. As per our discussion, IBuilder contains 4 members, Sum, Divide, Multiply & substract.
public interface IBuilder { float Sum(int firstnum, int secondnum); float Substract(int firstnum, int secondnum); float Multiply(int firstnum, int secondnum); float Divide(int firstnum, int secondnum); }
Download Sample Application - 66 KB
Saturday, October 23, 2010
DLR using Reflection.Emit (In Depth) Part 1
I love C#, I Love .NET. Do you agree ? Hmm, But I mean it :)
Well, lets put it in other words, " The more I see the framework, the more I discover in .NET". Yes, after putting my efforts with Reflection classes, I thought I could make some research on code generation. I took the CodeDom being the best alternative to generate code. Sooner or later, I found out, CodeDom actually allows you to build your assembly but it is does not allow you to dynamically compile a part of the assembly at runtime, but rather it invokes the compiler to do that. So rather than CodeDom, I thought there must be something else which fruits my needs.
Next I found out one, using Expression Trees. If you are already following me, I think you know, few days back I have already written about Expression Trees and Lamda Decomposition. So it is not a good time to recap the same. Later on, I did some research on MSIL, and found it worth learning. If you are going to grow with .NET, it would be your added advantage if you know about MSIL. Hence I started looking at the MSIL. Finally I found out a number of classes which might help you to build a Type dynamically. Let me share the entire thing with you.
Introduction
Reflection.Emit like CodeDom allows you to build your custom assembly and provides you a number of Builder classes which might be compiled during Runtime, and hence invoke DLR capabilities of C#. The library also exposes one ILGenerator which might be used later to produce the actual MSIL by putting efforts to emit Operation codes. So finally after you write your OpCodes correctly, you could easily able to compile the type dynamically during runtime. In this post, I would use ILDASM to see the IL generated from our own class, that I define, and later on I would try to build the same class dynamically.
What is Reflection ?
If you are struck with Reflection, then you need to really gear yourself a bit to go further. Let me give a brief explanation of Reflection. Reflection is actually a technique to read a managed dll which is not being referenced from the application and call its types. In other words, it is a mechanism to discover the types and call its properties at runtime. Say for instance, you have an external dll which writes logger information and sends to the server. In that case, you have two options.
To know more try Reflection Overview
What is Reflection.Emit ?
Being a part of Reflection, Reflection.Emit namespace list you a number of classes which you can use to build your type. As I have already told you, Reflection.Emit actually provides you some Builder classes like AssemblyBuilder, ModuleBuilder, ConstructorBuilder, MethodBuilder, EventBuilder, PropertyBuilder etc. which allows you to build your IL dynamically during run time. The ILGenerator provides you the capabilities to generate your IL and place the same for a method. Generally, it is very rare that a developer need these capabilities to generate an assembly at runtime, but it is great to find these capabilities present in the framework.
Now lets see what is required to build an assembly.
Well, lets put it in other words, " The more I see the framework, the more I discover in .NET". Yes, after putting my efforts with Reflection classes, I thought I could make some research on code generation. I took the CodeDom being the best alternative to generate code. Sooner or later, I found out, CodeDom actually allows you to build your assembly but it is does not allow you to dynamically compile a part of the assembly at runtime, but rather it invokes the compiler to do that. So rather than CodeDom, I thought there must be something else which fruits my needs.
Next I found out one, using Expression Trees. If you are already following me, I think you know, few days back I have already written about Expression Trees and Lamda Decomposition. So it is not a good time to recap the same. Later on, I did some research on MSIL, and found it worth learning. If you are going to grow with .NET, it would be your added advantage if you know about MSIL. Hence I started looking at the MSIL. Finally I found out a number of classes which might help you to build a Type dynamically. Let me share the entire thing with you.
Introduction
Reflection.Emit like CodeDom allows you to build your custom assembly and provides you a number of Builder classes which might be compiled during Runtime, and hence invoke DLR capabilities of C#. The library also exposes one ILGenerator which might be used later to produce the actual MSIL by putting efforts to emit Operation codes. So finally after you write your OpCodes correctly, you could easily able to compile the type dynamically during runtime. In this post, I would use ILDASM to see the IL generated from our own class, that I define, and later on I would try to build the same class dynamically.
What is Reflection ?
If you are struck with Reflection, then you need to really gear yourself a bit to go further. Let me give a brief explanation of Reflection. Reflection is actually a technique to read a managed dll which is not being referenced from the application and call its types. In other words, it is a mechanism to discover the types and call its properties at runtime. Say for instance, you have an external dll which writes logger information and sends to the server. In that case, you have two options.
- You refer to the assembly directly and call its methods.
- You use Reflection to load the assembly and call it using interfaces.
To know more try Reflection Overview
What is Reflection.Emit ?
Being a part of Reflection, Reflection.Emit namespace list you a number of classes which you can use to build your type. As I have already told you, Reflection.Emit actually provides you some Builder classes like AssemblyBuilder, ModuleBuilder, ConstructorBuilder, MethodBuilder, EventBuilder, PropertyBuilder etc. which allows you to build your IL dynamically during run time. The ILGenerator provides you the capabilities to generate your IL and place the same for a method. Generally, it is very rare that a developer need these capabilities to generate an assembly at runtime, but it is great to find these capabilities present in the framework.
Now lets see what is required to build an assembly.
Subscribe to:
Posts (Atom)
Author's new book
Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!
Grab it now !!!