Posts Tagged ‘C#’

In the last post related to Roslyn we developed a very basic syntax walker. In this post we will see how we can use the same for code analysis and checking. As a good practice we generally try to avoid having instance members in a singleton class. This is true if you are making your business logic layer classes Singleton and would prefer to avoid mess up by multiple threads. In order to check that we need to check the following:

a) Whether the class has any instance fields or properties

b) Whether class is a singleton i.e having a private constructor

Let’s consider the following singleton class:

(more…)

The Roslyn project aims to expose the functionalities of C#/VB complier as API/Services. The Roslyn CTP was released this October.One of the important components of Roslyn is the Compiler API. This exposes an object model which provides access to information generated at the different stages of compilation.The first phase of any compilation process involves parsing and generating the syntax tree. In this post we will discuss about the basics of the Syntax Tree API.

(more…)

Inside C# Extension Methods

Posted: October 23, 2011 in .NET, C#
Tags: ,

C# Extension methods were introduced in C# 3.0. They provide a mechanism to extend(not the inheritance way) the functionality of an existing class by attaching methods to it.An extension method needs to be developed in a static class as a static method as shown below:

public static class MyExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

We can invoke it as

10.AddExt(12)

In this post we will look at what’s happening inside extension method.

To understand the difference I am adding one more static method of exactly same signature.

public static class MyExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

The two methods are invoked as:

static void Main(string[] args) 
        { 
            Console.WriteLine(10.AddExt(12)); 
            Console.WriteLine(MyExtensions.AddStatic(10,12)); 
            Console.Read(); 
        }

Let’s take a look into the IL code of the two method calls.

ext

The IL code of the two method calls are exactly same and they are just static method calls. Only in case of AddExt the object on which it is invoked in C# code is passed as first parameter value.

So what’s going on ? We have to go to the IL for method definitions:

image

image

Only visible difference is the extension method has an attribute called ExtensionAttribute injected on the IL code. Let’s add this attribute to the other static method and see what happens?

This leads to a compiler error “Do not use ‘System.Runtime.CompilerServices.ExtensionAttribute’. Use the ‘this’ keyword instead.”

So Mr. compiler is not allowing us to hack around with his magic wand of syntactic sugar.

However we can summarize as:

  • When we write an extension method using “this” keyword in the first parameter compiler injects a ExtensionMethodAttribute to the IL code of the method.
  • The invoking code for an extension is replaced as <Static Class Name>.<ExtensionMethodName>(<Object Instance on which method is invoked>,…….)

Hang on.. What if there are two classes with same extension method name on same class e.g. if we add something like:

public static class MyOtherExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

We immediately get a compiler error “The call is ambiguous between the following methods or properties: ‘ExtensionMethods.MyExtensions.AddExt(int, int)’ and ‘ExtensionMethods.MyOtherExtensions.AddExt(int, int)

If I define the extension method on a dynamic type as

public static Int32 AddExt(this dynamic i, Int32 j) 
{ 
            return i + j; 
}

Again compiler stops us from so with a message “The first parameter of an extension method cannot be of type ‘dynamic’

We will go for a generic parameter now.

public static Int32 AddExt<T>(this T i, Int32 j) 
        { 
            return ++j; 
        }

This one compiles. But which will be invoked? MyExtensions.AddExt or MyOtherExtensions.AddExt.

static void Main(string[] args) 
       { 
           Console.WriteLine(10.AddExt(12)); 
           Console.WriteLine(new Object().AddExt(12));

           Console.WriteLine(MyExtensions.AddStatic(10, 12)); 
           Console.Read(); 
       } 


public static class MyExtensions 
    { 
        public static Int32 AddExt<T>(this T i, Int32 j) 
        { 
            return ++j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    } 
    public static class MyOtherExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

It is MyOtherExtensions.AddExt that is compiler finds the closest match while generating the IL Code.

image

So Extension methods are nothing but static calls accepting the object instance on which it is invoked (as if instance method) as the first parameter.

The last question we they can only be added in static classes. I think that’s good design decision.

  • Extension methods are supposed to act & designed like instance method on some other classes
  • We can’t add global methods without classes in C# every method needs a class container
  • But extension methods are not supposed be aware of instance properties of the class they belong to as that is a mere container for them.
  • So best way is to enforce through the complier that extension methods are within static classes

In this post we will discuss about different techniques of sorting collections of objects in C# using the functions provided by the base class libraries.This is something very common and there different types of provisions in .NET BCL to achieve the same.We will try to discuss the advantages and limitations of each of these approaches.

I will start with the most simplest of all the techniques that is implementing the interface IComparable<T>. The IComparable<T> has the following methods:

  • int CompareTo(T other) – This method compares one instance of object of type T with another which is passed as parameter.

The following class implements an IComparable<T> interface as shown below:

public class Member : IComparable<Member> 
    { 
        public int ID { get; set; } 
        public String FirstName { get; set; } 
        public String LastName { get; set; } 
        public DateTime DateOfJoining { get; set; }


        public int CompareTo(Member other) 
        { 
            return this.ID.CompareTo(other.ID); 
        } 
    }

Here the comparison is done based on the property ID of the member class. The following snippet is used to demonstrate the usage.

List<Member> ls = new List<Member>() 
                                { 
                                    new Member(){ID=1,FirstName="John",LastName="Doe"}, 
                                    new Member(){ID=3,FirstName="Allan",LastName="Jones"}, 
                                    new Member(){ID=2,FirstName="Martin",LastName="Moe"}, 
                                    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"} 
                                }; 
ls.Sort(); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

Here the output will be sorted by ID as shown below:

Member John:Doe
Member Martin:Moe
Member Allan:Jones
Member Ludwig:Issac

Now if we want to sort by other properties as well like FirstName, LastName etc. One crud approach is to create different subclasses as shown below:

public class MemberByFirstName : Member, IComparable<MemberByFirstName> 
    { 
        public int CompareTo(MemberByFirstName other) 
        { 
            return this.FirstName.CompareTo(other.FirstName); 
        } 
    }

Then when we need to sort by say FirstName we will use List of this sub class as shown below:

List<MemberByFirstName> ls = new List<MemberByFirstName>() 
{ 
            new MemberByFirstName(){ID=1,FirstName="John",LastName="Doe"}, 
            new MemberByFirstName(){ID=3,FirstName="Allan",LastName="Jones"}, 
            new MemberByFirstName(){ID=2,FirstName="Martin",LastName="Moe"}, 
            new MemberByFirstName(){ID=4,FirstName="Ludwig",LastName="Issac"} 
}; 
ls.Sort(); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

The output will be alphabetically sorted by FirstName as shown below:

Member Allan:Jones
Member John:Doe
Member Ludwig:Issac
Member Martin:Moe

But this is a cumbersome and rigid approach.Similar stuff can be implemented in a much more cleaner way using the IComparer<T> interface.This interface defines the following method:

  • int Compare(T x,T y) – This method takes two objects of type T and compares between them.

We can implement IComparer<T> as shown below:

public class MemberSorterByLastName : IComparer<Member> 
   {

       public int Compare(Member x, Member y) 
       { 
           return x.LastName.CompareTo(y.LastName); 
       } 
   } 
   public class MemberSorterByFirstName : IComparer<Member> 
   {

       public int Compare(Member x, Member y) 
       { 
           return x.FirstName.CompareTo(y.FirstName); 
       } 
   } 
  

We can use the method Sort(IComparer comparer) as shown below to sort the List of Member by FirstName and LastName respectively:

List<Member> ls = new List<Member>() 
                                { 
                                    new Member(){ID=1,FirstName="John",LastName="Doe"}, 
                                    new Member(){ID=3,FirstName="Allan",LastName="Jones"}, 
                                    new Member(){ID=2,FirstName="Martin",LastName="Moe"}, 
                                    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"} 
                                };

ls.Sort(new MemberSorterByFirstName());

ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

ls.Sort(new MemberSorterByLastName());

ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

This approach is clean but has the overhead of creating separate classes for each different sort criteria.This can be achieved much more simply using the Comparison<T> delegate. The Comparison<T> delegate has the following signature:

  • public delegate int Comparison<in T>(T x,T y) – This is used to compare two objects of generic type T.

We can use the Sort (Comparison<T> comparison) method as shown below:

List<Member> ls = new List<Member>() 
                    { 
                        new Member(){ID=1,FirstName="John",LastName="Doe"}, 
                        new Member(){ID=3,FirstName="Allan",LastName="Jones"}, 
                        new Member(){ID=2,FirstName="Martin",LastName="Moe"}, 
                        new Member(){ID=4,FirstName="Ludwig",LastName="Issac"} 
                    };

ls.Sort((x, y) => x.FirstName.CompareTo(y.FirstName)); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName));

ls.Sort((x, y) => x.LastName.CompareTo(y.LastName)); 
ls.ForEach(m => Console.WriteLine("Member " + m.FirstName + ":" + m.LastName)); 

By far this approach is the most simplest one. In other languages like Java the first two options are there e.g. Java Comparer interface is similar to IComparable and Comparator interface is similar to IComparer in C# respectively. But Java is yet to have support for Closures so the third approach is still not possible.

In this post and couple of posts to follow, we will discuss about the different type casting mechanisms supported by CLR and the three primary CLR supported languages C#,VB.NET and C++/CLI.To start with, lets take a look into the two possible kinds of conversion scenarios, that generally we come across.

(more…)

Covariance & Contravariance – Delegates in C#

Posted: November 30, 2008 in .NET
Tags: ,

In my last post I had discussed about delegates in C# but intentionally skipped the covariance and contravariance with respect to delegates.I would like to discuss the concepts of covariance and contravariance in general first and then correlate the same in context of C# delegates.The concept of covariance and contravariance I found a bit confusing and counterintuitive initially.

Let us consider a type/class P and let P” be a subtype/subclass of T.We will denote this relationship as P”->P for sake of discussion.Based on this inheritance relationship following statements are true:

  1. Domain of P is much broader than P”.
  2. Any context where P is expected we can substitute it by P” [Liskov Substitution Principle]

Similarly we have another pair of classes R and R” where R”->R.

Now we will consider a function f which type P as parameter and returns type R.We will denote this as R f(P).Similarly there is another function f” as R”f”(P”) which accepts P” as parameter and returns type R”.

Can we say that f”->f or we can replace f by f” in any context?

In order to replace f by f”, f” should be able to handle parameter of type P and return value of type R.

Now R” is a subclass of R,so R” is a type of R.Hence we can say f” basically returns a type R.This is covariance by which we can replace a method by another having a more derived return type.

Now let’s see can f” handle a parameter of type P.The answer is NO.The logic built into f” is only for the possible values of P” and P can have more possible values than P” as it is the super class.So f” will malfunction for all those values of P which are outside the range of P”.So f” can replace f only if parameter of f is more derived than that of f”.This is contravariance by which we can replace a method by another having parameter types that are less derived.

If we redefine f as R f(P”) and f” as R” f”(P) then we can say f”->f and can replace f in any context.

Now let us consider an example with some real life examples.

There is a base class called Order and Order can be of two derived types say SalesOrder and PurchaseOrder.Similarly there is a base class called AccountRecord and there are two derived classes say AccountPayable and AccountReceivable.

There are two methods

  1. M1 – AccountRecord GetAccountInfo(Order o)
  2. M2 – AccountPayable GetAccountInfo(PurchaseOrder po)

M2 cannot accept a variable of type O as parameter because if it is an instance of SalesOrder instead of PurchaseOrder this will fail.

But calling code which expects AccountRecord as output can very well handle both AccountPayable and AccountReceivable.

We can relate this to a delegate in the following way:

public delegate object ReadObjectDelegate(FileStream fs)

We can attach the following method to this delegate

public string Read(Stream s)

This is because Stream is less derived than FileStream and string is more derived than object

Delegates in C#

Posted: November 29, 2008 in .NET
Tags: ,

Most of us quite familiar with the delegate keyword in C#.Delegates provides us with a mechanism to encapsulate a method or multiple methods.These are quite like managed version of function pointers in C#.We normally use delegates to define callback methods.

First we need to define a delegate as a type with it’s signature as shown below.Note here the signature includes both parameters as well as return values.

public delegate void DemoDelegate(int i);

To use the delegate we need define a variable to type DemoDelegate ,instantiate the variable by passing a method name of matching signature and then invoke the delegate by passing suitable parameter values as shown in the snippet below:

class DelegateSample
   {
       public void ShowDemo()
       {
 
          DemoDelegate d = new DemoDelegate(Test); //Create instance
           d(10); //Invoke delegate
       }
       public void Test(int i)
       {
           Console.WriteLine(“Method Test called with parameter ” + i);
       }
   }

Now if we take close look into the syntactic details we see all the operation related to delegate closely resembles that of a reference type.So what’s going on inside.On taking a look into the IL code of the assembly we found a new class is generated as shown below:

.class /*02000003*/ public auto ansi sealed DelegateDemo.DemoDelegate
       extends [mscorlib/*23000001*/]System.MulticastDelegate/*01000002*/
{

……….
} // end of class DelegateDemo.DemoDelegate

So the C# compiler internally generates a class with the same name as the delegate type and it inherits from a class System.MulticastDelegate.The class System.MulticastDelegate is derived from base class System.Delegate.This method provides two public attributes

  1. Method – Metadata Method which is getting executed as an instance of System.Reflection.MethodInfo
  2. Target – Stores the instance on which delegate method executes.

Before we proceed further let us take a quick look into another feature of delegate chaining.Refer to the sample below and refer to the lines marked in red.

class DelegateSample
  {
      public void ShowDemo()
      {
          DemoDelegate d1 = new DemoDelegate(Test);
          DemoDelegate d2 = new DemoDelegate(Demo);
          Console.WriteLine(“Delegate Added”);
          DemoDelegate d3 = d1 + d2; //Two delegates are combined
          d3(10); //First method  Test and then Demo is invoked
          Console.WriteLine(“Delegate Removed”);
          DemoDelegate d4 = d3 – d1; //One delegate is removed from the combination
          d4(10);  //Only method Demo is invoked as delegate d1 is removed.
      }
      public void Demo(int i)
      {
          Console.WriteLine(“Method Demo called with parameter ” + i);
      }
      public void Test(int i)
      {
          Console.WriteLine(“Method Test called with parameter ” + i);
      }

What happens when I do + and – operation on delegates.Internally the methods System.Delegate.Combine and System.Delegate.Remove is invoked by the runtime.This we can see in the IL code of the show demo method:

.method public hidebysig instance void  ShowDemo() cil managed
{

  …………..

  IL_0028:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
                                                                                          class [mscorlib]System.Delegate)
  ……………

  IL_0049:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
                                                                                         class [mscorlib]System.Delegate)
  ……………..

} // end of method DelegateSample::ShowDemo