Archive for October, 2011

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

REST/HTTP Services in WCF is nothing new, it’s been there since 2008, version 3.5 of the framework. Yesterday I came across a question that whether a particular operation can support both XML/JSON format and return response in the suitable format as demanded by the client program. To my knowledge the answer was a both Yes & No. Because I did quite extensive study of the System.ServiceModel.Web.WebHttpBehavior and System.ServiceModel.Web.WebGetAttribute back in 2008 as given in the post below:

https://sankarsan.wordpress.com/2008/10/28/wcf-web-model-poxjson-support/

This limitation drew my attention. However there was a solution to the problem.We can always extend the WebHttpBehavior and override the WebHttpBehavior.GetReplyDispatchFormatter method to return our own custom implementation of System.ServiceModel.Dispatcher.IDispatchFormatter. A similar implementation can be found in the post below:

http://damianblog.com/2008/10/31/wcf-rest-dynamic-response/

Wait …..

This kind of an implementation is actually now part of the .NET 4.0. This is controlled by the automaticFormatSelectionEnabled property of the WebHttpBehavior. This property when set to true then the response format of the operation is governed by the Accept , Content-Type header of the request. This feature is called Automatic Format Selection. This is what we will discuss in this post.

I have a simple service with a Add operation as shown below:

[OperationContract] 
[WebGet] 
public int  Add(int i , int j) 
{ 
   // Add your operation implementation here 
   return i+j; 
} 

The client code is a .NET program sending a HTTP request as shown below:

HttpWebRequest request = HttpWebRequest.Create("http://localhost:5072/TestService.svc/Add?i=1&j=1") as HttpWebRequest; 
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None; 
request.Method = "GET"; 
request.ContentType = "text/xml"; 
request.Accept = "text/xml"; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
using (StreamReader rdr = new StreamReader(response.GetResponseStream())) 
{ 
    Console.WriteLine(rdr.ReadToEnd()); 
}

The response is in JSON format as shown below:

{"d":2}

Now I will turn on auto format selection as shown below using config.

wcfauto

Now the output is XML as shown below:

<AddResponse xmlns="http://sankarsanbose.com/test"><AddResult>2</AddResult></Add 
Response>

Now I will change the Accept header to JSON.

request.ContentType = "text/xml"; 
request.Accept = "text/json";

The response is now again in JSON format as shown below:

{"d":2}

NOTE: If both Accept and Content-Type are specified then Accept takes the higher priority.

What happens if I set the response format in WebGetAttribute? Say I make it Json as shown below:

[OperationContract] 
        [WebGet(ResponseFormat=WebMessageFormat.Json)] 
        public int  Add(int i , int j) 
        { 
            // Add your operation implementation here 
            return i+j; 
        }

The output is driven by Accept Header and is in XML format

<AddResponse xmlns="http://sankarsanbose.com/test"><AddResult>2</AddResult></Add 
Response> 

If I change the headers to JSON obviously the output is JSON.

Now I am changing the ResponseFormat to XML as shown below:

[WebGet(ResponseFormat=WebMessageFormat.Xml)] 

The request headers are set as shown below:

request.ContentType = "text/json"; 
request.Accept = "text/json"; 

The output surprisingly is just 2 neither JSON nor XML.

The request headers are changed back to XML

request.ContentType = "text/xml";
request.Accept = "text/xml";

Now the output is XML is as shown below:

 
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">2</int>

This is clearly different from structure of the XML generated earlier. Seems to be using the different serializer.

I was not able to articulate the reason for the above two anomalies very clearly. But I think when auto format selection is enabled then providing the ResponseFormat does not make much sense.