Archive for the ‘C#’ Category

Singleton is the most widely known Design Pattern. Singleton makes sure that one only one instance of a class is created and the same instance is used by other programs and classes.An implementation of a Singleton class is shown below:

(more…)

new Keyword in C#

Posted: July 29, 2012 in .NET, C#
Tags:

The “new” keyword in C# is one of the most commonly known and used keywords in C#.It is used as an operator for instantiating objects of a class as shown below.

(more…)

In the last post we have discussed at length about different mechanisms of parameter passing and obtaining results from a workflow.In this post we will discuss about another extremely important aspect of workflow and host communication i.e. Bookmarks. Bookmarks as the name suggests is a like Bookmark for a book. When created at a particular point in the execution of the workflow , the execution is suspended and the workflow waits to be resumed.When a bookmark is resumed it starts executing exactly from the same point.

(more…)

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