You must be thinking why I am coming with such a strange Tag line today. Actually if you go on reading you would definitely understand what I am speaking on. In my last post, I have pointed out that Tuple is implemented in a strange way. If you see the 8th implementation of Tuple class, the one with 8 generic parameters, you will see, it gives a restriction to the last parameter TRest to allow only Tuple.
But the strange thing is, the restriction is not open. The Tuple class does not have this restriction specified in its generic type parameter TRest. So you can even declare the last argument as string, but when your application actually tries to create an object of it, the application will throw an ArgumentException.
This seemed to be very weird to me. I was thinking why did Microsoft did not put this in Type argument, making ITuple (an internal implementation) public, or create a special sealed class, and expose the same as a constraint to Type argument. I think this could be answered only by BCL Team.
Download Sample Code - 30KB
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.
Thursday, November 4, 2010
Wednesday, November 3, 2010
Working with Tuple in C# 4.0
After writing about C# 5.0, you might think why I moved a step behind with C# 4.0. Hey, I will definitely keep my promise to write a good blog on new async and await feature, but because of time it is taking a bit time to go on. C# 4.0 being officially released contains lots of thoughts and approaches that comes handy in many places. There are lots of new features introduced with C# 4.0 where a few of them are really very handy.
Today, I will write about a very handy object introduced in FCL named Tuple which can store n - number of values in it. Yes, you specify the type of each of those variables as generic parameters, and the object will create those values for you. Lets see how it works.
Using a Tuple
Base class library exposes two objects. It exposes the static class Tuple which allows you to get a number of Tuple instances based on the Static method Create, and a number of Tuple classes, each of which takes some specific number of Generic arguments.
Today, I will write about a very handy object introduced in FCL named Tuple which can store n - number of values in it. Yes, you specify the type of each of those variables as generic parameters, and the object will create those values for you. Lets see how it works.
Using a Tuple
Base class library exposes two objects. It exposes the static class Tuple which allows you to get a number of Tuple instances based on the Static method Create, and a number of Tuple classes, each of which takes some specific number of Generic arguments.
- Tuple.Create<t1>
- Tuple.Create<t1,t2>
- Tuple.Create<t1,t2,t3>
- Tuple.Create<t1,t2,t3,t4>
- Tuple.Create<t1,t2,t3,t4,t5>
- Tuple.Create<t1,t2,t3,t4,t5,t6>
- Tuple.Create<t1,t2,t3,t4,t5,t6,t7>
- Tuple.Create<t1,t2,t3,t4,t5,t6,t7,t8>
Friday, October 29, 2010
C# 5.0 Asynchronous Made Easy
After I introduced about Future Of C# 5.0 I was not aware of what Microsoft is thinking about it. But today after I saw PDC 2010 the main concern that Microsoft is pointing to on the release of C# 5.0 is the pain related to deal with asynchronous operations using Threads. It simplifies the existing MultiThreading model with Task based model, which now simplified with greater extent with the use of two new keywords yet not introduced as "await" and "async".
The History
Before the introduction of these features, we generally rely on traditional approaches of creating Thread from a ThreadPool and consuming a method which needed to be asynchronously called for. Again when the Thread finishes, or during the lifetime of the Thread we need callbacks to notify UI after a while, so that the user gets an impression that the background is updating the system. This breaks the way we write or the way we think of programming. The programmer needs to create the program to device in such a way that it handles continuity of the application by writing custom callbacks to the system or even use Dispatcher to update the UI thread from background. Thus the code becomes more and more complex as we add up more functionalities to the system.
The Present
In this PDC, Anders Hejlsberg introduces two new investments on C# which is probably now still in CTP to allow asynchronous calls to the applications very simple and easy to handle. The two keyword which were introduced recently are "async" and "await". Let me introduce these two keywords for the time being.
The History
Before the introduction of these features, we generally rely on traditional approaches of creating Thread from a ThreadPool and consuming a method which needed to be asynchronously called for. Again when the Thread finishes, or during the lifetime of the Thread we need callbacks to notify UI after a while, so that the user gets an impression that the background is updating the system. This breaks the way we write or the way we think of programming. The programmer needs to create the program to device in such a way that it handles continuity of the application by writing custom callbacks to the system or even use Dispatcher to update the UI thread from background. Thus the code becomes more and more complex as we add up more functionalities to the system.
The Present
In this PDC, Anders Hejlsberg introduces two new investments on C# which is probably now still in CTP to allow asynchronous calls to the applications very simple and easy to handle. The two keyword which were introduced recently are "async" and "await". Let me introduce these two keywords for the time being.
Monday, October 25, 2010
Create Enumeration as Bit Flags
Enumeration is one the important feature of C#. Enumeration allows you to name a variable to make sense for the program. It is in general impossible to understand numeric status values when there is more than two values for a single state of object. In such a case we give a logical name for the numeric integer and use the Logical name of it to call that particular state.
For instance :
Say you want to define the nature of a person.
Hmm... Putting it further, Enum might also come very handy when you want to use a combination of the same. Say for instance, a person can be both Logical and Caring. Now how could you define this? Do you need to define enumeration values for each of them ? I guess that would not be a good choice either.
Flags attribute in Enum plays a vital role if you want to use the values of an enumeration in combinations. So that each combination of enumeration values are mutually exclusive and does not overlap with another value of Enum. For bit fields, it is very easy and yet very handy to use Flags attribute rather than using your own logic to define the flags yourself.
For instance :
Say you want to define the nature of a person.
public enum Character { Caring, Honest, Loving, Desparate, Obedient, Logical, Practical }You might name these characteristics using numeric values, say you have Honest as 1, Loving as 2 etc. But it would be more logical to use an Enum instead.
Hmm... Putting it further, Enum might also come very handy when you want to use a combination of the same. Say for instance, a person can be both Logical and Caring. Now how could you define this? Do you need to define enumeration values for each of them ? I guess that would not be a good choice either.
Flags attribute in Enum plays a vital role if you want to use the values of an enumeration in combinations. So that each combination of enumeration values are mutually exclusive and does not overlap with another value of Enum. For bit fields, it is very easy and yet very handy to use Flags attribute rather than using your own logic to define the flags yourself.
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.
Saturday, October 16, 2010
Hidden Facts of C# Structures in terms of MSIL
Did you ever thought of a program without using a single structure declared in it ? Never thought so na? I did that already but found it would be impossible to do that, at least it does not make sense as the whole program is internally running on messages passed from one module to another in terms of structures.
Well, well hold on. If you are thinking that I am talking about custom structures, you are then gone too far around. Actually I am just talking about declaration of ValueTypes. Yes, if you want to do a calculation, by any means you need an integer, and System.Int32 is actually a structure. So for my own program which runs without a single ValueType declared in it turns out to be a sequence of Print statements. Does'nt makes sense huh! Really, even I thought so. Thus I found it is meaningless to have a program which just calls a few library methods (taking away the fact that library methods can also create ValueType inside it) and prints arbitrary strings on the output window.
Please Note : As struct is actually an unit of ValueType, I have used it synonymously in the post.
So what makes us use Structures so often?
The first and foremost reason why we use structures is that
Well, well hold on. If you are thinking that I am talking about custom structures, you are then gone too far around. Actually I am just talking about declaration of ValueTypes. Yes, if you want to do a calculation, by any means you need an integer, and System.Int32 is actually a structure. So for my own program which runs without a single ValueType declared in it turns out to be a sequence of Print statements. Does'nt makes sense huh! Really, even I thought so. Thus I found it is meaningless to have a program which just calls a few library methods (taking away the fact that library methods can also create ValueType inside it) and prints arbitrary strings on the output window.
Please Note : As struct is actually an unit of ValueType, I have used it synonymously in the post.
So what makes us use Structures so often?
The first and foremost reason why we use structures is that
- They are very simple with fast accessibility.
- It is also created on Thread local stack, which makes it available only to the current scope and destroyed automatically after the call is returned. It doesn't need any external invisible body to clear up the memory allocated henceforth.
- Most of the primitives have already been declared as struct.
- In case of struct we are dealing with the object itself, rather than with the reference of it.
- Implicit and explicit operators work great with struct and most of them are included already to the API.
Labels:
.NET,
.NET 4.0,
C#,
CodeProject,
Memory Allocation
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 !!!