Wednesday, June 23, 2010

ILViewer

                This is an Add-in to Visual Studio

Description

                This helps us to view the MSIL (Microsoft Intermediate Language) generated for C# or VB.Net code we write.

Expected Users

                Those who are interested in studying -

                     How compiler is handling your code?

              How new language  features are implemented?

Example

                What is the MSIL equivalent for ‘property’ in C# or VB.Net?

         When you write a property in C#, compiler is generating some methods corresponding to it. Eventhough .property is there, the get_property and set_property methods are the working methods

                ie,

     public string Text { get; set; } is –

  1: .property instance string Text()
  2:  {
  3:    .get instance string Game.Classes.Dragger::get_Text()
  4:    .set instance void Game.Classes.Dragger::set_Text(string)
  5:  }
  6: 
  7:  .method public hidebysig specialname instance string 
  8:          get_Text() cil managed
  9:  {
 10:    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
 11:    // Code size       11 (0xb)
 12:    .maxstack  1
 13:    .locals init (string V_0)
 14:    IL_0000:  ldarg.0
 15:    IL_0001:  ldfld      string Game.Classes.Dragger::'<Text>k__BackingField'
 16:    IL_0006:  stloc.0
 17:    IL_0007:  br.s       IL_0009 
 18: 
 19:    IL_0009:  ldloc.0
 20:    IL_000a:  ret
 21:  } // end of method Dragger::get_Text 
 22: 
 23:  .method public hidebysig specialname instance void 
 24:          set_Text(string 'value') cil managed
 25:  {
 26:    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
 27:    // Code size       8 (0x8)
 28:    .maxstack  8
 29:    IL_0000:  ldarg.0
 30:    IL_0001:  ldarg.1
 31:    IL_0002:  stfld      string Game.Classes.Dragger::'<Text>k__BackingField'
 32:    IL_0007:  ret
 33:  } // end of method Dragger::set_Text
 34: 

Ie, for set and get methods with set_propertyName and get_propertyName are generated.

When you say – Text=”Hello”, compiler is doing – set_Text(“Hello”)

Use

                 Download ILViewer from http://ilviewer.codeplex.com/releases/view/59437 and install it.

Now you will  be able to see this plug in Visual Studio ‘Tools’ menu

clip_image002

Provide a shortcut key for ILViewer as –

                Go to: Tools => Environment => Keyboard

                Select ILViewer and provide shortcut key to be used. I am using ‘Ctrl+I’

                clip_image004

 

Open a .cs or .vb file in Visual Studio and run the ILViewer (press your shortcut key for ILViewer).

Now you can see the IL generated for your code file as a new file opened in Visual Studio.

 

clip_image006

Now you can select ‘New Horizonrtal Tab Group’ option from Windows menu.

clip_image008

This will create two windows: one for C# or VB.Net code and the other for IL.

clip_image010

After making changes in C# code, click short key for ILViewer and see the MSIL getting changed in lower pane.

Note:

1.       Whenever ILViewer is running, the focus should be in .cs or .vb file. Else you will get an error message as follows –

clip_image002

2.         Make sure that your code file doesn’t have any partial class, whose partial definition is in some other file . This results in compilation error.

Happy Learning

Monday, June 7, 2010

Transformation of delegates to Lambda

                 Lambda expressions are equivalent to delegates that we are using. To see how lambda expressions evolved, we have to start from basics –

C# 1.1 creating delegates

  1:   1: namespace Generics
  2:   2: {
  3:   3: 
  4:   4:     //Declare delegate
  5:   5:     public delegate void Message(string message); 
  6:   6: 
  7:   7:     class Lambda
  8:   8:     {
  9:   9:         public Message myMessage { get; set; }
 10:  10:         public Lambda()
 11:  11:         {
 12:  12:             //Define delegate
 13:  13:             myMessage = new Message(MessageLogic);
 14:  14:             //Invoke delegate
 15:  15:             myMessage("Hello");
 16:  16:         }
 17:  17: 
 18:  18:         public void MessageLogic(string message)
 19:  19:         {
 20:  20:             Console.WriteLine(message);
 21:  21:         }
 22:  22:     }
 23:  23: 
 24:  24: }
 25:  25: 
 26:  26: 

When we declare –

    public delegate void Message(string message);  

Compiler is declaring (generating) a type ‘Message’ which inherits from class ‘Delegate’. In this class an invoke method will be defined with the signature we are providing in the declaration line (In our case it is a void method that accepts a string).

Our focus is on line –

myMessage = new Message(MessageLogic);

This definition actually instantiates the class declared by compiler and passes the address of method, that suits the delegate signature, to the constructor

C# 2.0 delegates inference  

We can declare delegate as -

Message myMessage = new Message(MessageLogic);

But from the variable’s ‘myMessage’ type (here it is Message), compiler can infer the type of delegate to be passed. So we can avoid specifying it explicitly –

Message myMessage = MessageLogic;

 

C# 2.0 anonymous methods

In above example –

  1: Message myMessage = MessageLogic; 
  2: public void MessageLogic(string message) 
  3: { 
  4:    Console.WriteLine(message); 
  5: } 
  6: 
  7: 
  8: 

 

When we use anonymous method, we are defining the method on the fly-

Message myMessage = delegate(string message) { Console.WriteLine(message); };

Using this statement, compiler generates a method with the definition provided and create a delegate for it and assigns it to the variable ‘myMessage’ used.

 

C# 3.5 lambda expressions

 In anonymous method –

Message myMessage = delegate(string message) { Console.WriteLine(message); };

When we use lambda expression we don’t have to use keyword ‘delegate’ and compiler knows it is going to be a delegate

Message myMessage = (string message) => { Console.WriteLine(message); };

‘=>’ is pronounced as ‘goes to’

C# 3.5 lambda expression type inference    

Message myMessage = (string message) => { Console.WriteLine(message); };

From the variable type (Message), compiler knows what parameter types are going into the method. So we don’t have to specify the type separately

Message myMessage = (message) => { Console.WriteLine(message); };

 

C# 3.5 lambda expression enhancements

 Message myMessage = (message) => { Console.WriteLine(message); };

If there is only one argument for the method, then we can remove braces –

Message myMessage = message => { Console.WriteLine(message); };

Consider the case as follows –

  1: public delegate int Message(string message); 
  2: Message myMessage = delegate(string message) { return message.Length; }; 
  3: 
  4: 
  5: 

In this expression there is only one statement in function definition and that is a return statement. So we don’t have to use curly braces and ‘return’ keyword

Message myMessage = message => message.Length;

 

Example:

 List<string> list = new List<string> { "Hello", "World" };

From this list I need to filter items contains ‘r’

 Where

You can see that ‘Where’ is accepting a delegate of type ‘Func<string,bool>’.

Func and Action are two delegate types provided by framework. Former can be used for functions (return is there) and latter for methods (void type)

 

So Func<string,bool> means it is a delegate that accepts string parameter and returns a bool value.

IEnumerable<string> selectedList = list.Where(i => i.Contains("r"));

We passed delegate as ‘i => i.Contains("r")’, this means inside the ‘Where’ method, it takes each item in the collection ‘list’ and apply our delegate. From our anonymous method we are returning true only for items that contains ’r’. If function returns true, that item will be added to the output collection ‘selectedList’.

In effect we get a collection with one item ‘World’

So what ever we were doing in the past is actually happening now also. The only difference is compiler exposes some easy ways for us to do things and the head ache of converting it to actual definitions is taken by more intelligent compiler.

We can look forward for more intelligent compiler that reduces developers work.

 

 

 

 

 

 

 

 

 

Generics Overview

 

In this article we will discuss –

1.       Why we need generics?

2.       How to implement Generics?

3.       How compiler helps us?

4.       Other features

 

Why we need generics?              

To get the relevance of generics we have to walk through C# 1.1 world.

Performance issue in 1.1

Consider the case where we need to have a class that deals with any type. The class will be like –

  1: public class GenericClass
  2:     {
  3:         public object a { get; set; }
  4:         public object Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 
 

If I want to deal with integer type on this class –

  1: GenericClass myGenericClass = new GenericClass();
  2: myGenericClass.a = 1;
  3: int b = (int)myGenericClass.Invoke();

                In this case the integer value 1 is assigned to object property. Integer is a value type and hence to hold this integer value, a new object is created in memory and the integer value is taken into it. This is called boxing.

                When you are retrieving the integer value back to ‘b’, the integer value stored in the object is retrieved. This is unboxing.

                So obviously boxing and unboxing takes more memory and more time, When we deal with large collections, this memory and time consumption is signinificant that it reduces the overall performance.

Consider the case of dealing with reference types -

  1: GenericClass myGenericClass = new GenericClass();
  2: myGenericClass.a = "1" ;
  3: string b = (string)myGenericClass.Invoke();
  4: 

                 A string object is assigned to the property ‘a’ and the same is retrieved from ‘Invoke()’ to ‘b’. This actually involves Casting from one type to another (String to Object and Object to String). This also affects performance.

Solution in 1.1

                We can resolve this performance issue by making our class strongly typed. Ie, for using integer types, define class as –

  1: public class IntClass
  2:     {
  3:         public int a { get; set; }
  4:         public int Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 

For string-

  1: public class StringClass
  2:     {
  3:         public string a { get; set; }
  4:         public string Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 

                When we use such strongly typed classes, boxing, unboxing and casting will be avoided and hence the performance will be enhanced.

Drawback for 1.1 solution

                We can go for separate class declarations for each type (string, int, etc). But if you are using this class declaration for ‘n’ types, you have to declare ‘n’ different classes (differ only in type used inside the method).

Solution in 2.0

                From above examples you can see that different classes we declare is following same template and the type is replaced with the type we need.

                In 2.0 generics concept is introduced to avoid the headache of declaring different classes for types we need.

 

In generics the things that we discussed above is split among developer and compiler -

How to implement Generics?

                For above mentioned example, generic class is -

  1: public class GenericClass<T>
  2:     {
  3:         public T a { get; set; }
  4:         public T Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 
 10: 

                It is nothing but you declared a class that can be used as template for class declaration using any type.

When you define a variable for generic class –

  1: GenericClass<int> intClass = new GenericClass<int>();

The type you need is passed instead of ‘T’ in declaration.

So developer simply declares the template and request for a class declared for the type he needed.

How compiler helps us?

When developer defines variable as –

  1: GenericClass<int> intClass = new GenericClass<int>();

                Compiler access the template defined and replaces all ‘T’s with type requested by developer and eventually declares a new class as –

  1: public class IntGenericClass
  2:     {
  3:         public int a { get; set; }
  4:         public int Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 
 10: 

 

                Then the variable ‘intClass’ points to the instance created for new class declared ‘IntGenericClass’.

                By this way the strongly typed classes are defined by compiler for any type you need.

Other features

                You can restrict the types that can be used to declare classes from your generic template.

Type constraint

  1: public class GenericClass<T> where T : IList,ICollection 
  2:     {
  3:         public T a { get; set; }
  4:         public T Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 
 10: 

                This is called type constraint where you are saying ‘T’ should implement interface ‘IList’ and ‘ICollection’.

                So in this case you can define –

  1: GenericClass<ArrayList> arrayClass = new GenericClass<ArrayList>();

 

Because ArrayList is implementing IList and ICollection.

But you cannot do following definition –

  1: GenericClass<int> intClass = new GenericClass<int>();

  1: public class GenericClass<T> where T : class 
  2:     {
  3:         public T a { get; set; }
  4:         public T Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 
 10: 

                This means you can use only refernce types as ‘T’.

Right-

  1: GenericClass<ArrayList> arrayClass = new GenericClass<ArrayList>();

Wrong –

  1: GenericClass<int> intClass = new GenericClass<int>();

Constructor Constraint

  1: public class GenericClass<T> where T : new()
  2:     {
  3:         public T a { get; set; }
  4:         public T Invoke()
  5:         {
  6:             return a;
  7:         }
  8:     }
  9: 
 10: 

              

 This says that ‘T’ should have the default constructor

                Right –

  1:                                 GenericClass<ArrayList> arrayClass = new GenericClass<ArrayList>();

                Wrong –

  1: GenericClass<string> stringClass = new GenericClass<string>();

You can make use of Type constraint and constructor constraint at the same time -

  1: public class GenericClass<T> where T :IList, new()
  2:     {
  3:         public T a { get; set; }
  4:         public T Invoke()
  5:         {
  6:             return a;
  7:         }
  8: }
  9: 
 10: