How extension method works in .Net

What is extension method

Here is the Wikipedia definition – In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are permitted by some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.

Extension method introduced in .Net Framework 3.0. The implementation is little different in C# and VB.Net. In C# extension method implemented as static methods in static classes, with the first argument being of extended class and preceded by “this” keyword. And in VB.Net extension method are recognized by the presence of the “extension” keyword or attribute. The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type “dot” after an instance of an IEnumerable type such as List or Array.

Here is a simple extension methods, which reverses a string.

class Program
{
    private static void Main(string[] args)
    {
        string name = "dotnetthoughts";
        Console.WriteLine(name.Reverse());
    }
}

static class Extensions
{
    public static string Reverse(this string name)
    {
        var result = string.Empty;
        var chars = name.ToCharArray();
        for (int i = chars.Length - 1; i >= 0; i--)
        {
            result += chars[i];
        }

        return result;
    }
}

If you look into the code, by default string doesn’t have a method like Reverse. And you can find a static class Extensions, which has a Reverse() static method, with the first argument being of extended class and preceded by “this” keyword, it an a extension method for string class. Because of this, compiler will compile the source without any problem.

How it works.

If you look into the IL code generated using IL Disassembler, you can find a type like Extensions which is decorated with ExtensionAttribute, this is the same attribute you need to create an extension method in VB.Net. In C#, if you use this modifier for the first parameter of extension method, compiler will automatically emit ExtensionAttribute for the methods.

Extension Attribute in IL Code

Extension Attribute in IL Code

And in the consuming code, it is like invoking a static method.

IL Main - Invoking static method

IL Main – Invoking static method

General guidelines to implement Extension Methods

  • An extension method will never be called if it has the same signature as a method defined in the type.
  • Extension methods are brought into scope at the namespace level.

Happy Coding

Why you shouldn’t believe in your favorite .net decompiler

Yesterday I posted about explicit interface implementation. I was curious about to know how CLR treats Explicit interface implementation. I looked into the generated IL code using IL DASM, and it was pretty similar to C# code I wrote. So I thought of reverse engineering the assembly. I verified the assembly with five .net decompilers. And only two provided the compilable code. Here is the .Net decompilers I used.

This the code I compiled.

static void Main(string[] args)
{
    ISample sample = new Sample();
    var result = sample.Add(10, 20);
    Console.WriteLine(result);  //Will return 30

    ISample2 sample2 = new Sample();
    var result2 = sample2.Add(10, 20);
    Console.WriteLine(result2);  //Will return 40
}

And here is the code from decompilers.

ILSpy

// ConsoleApplication6.Program
private static void Main(string[] args)
{
	ISample sample = new Sample();
	int value = sample.Add(10, 20);
	Console.WriteLine(value);
	ISample2 sample2 = new Sample();
	int value2 = sample2.Add(10, 20);
	Console.WriteLine(value2);
}

dotPeek

private static void Main(string[] args)
{
    Console.WriteLine(new Sample().Add(10, 20));
    Console.WriteLine(new Sample().Add(10, 20));
}

JustDecompile

private static void Main(string[] args)
{
    Console.WriteLine((new Sample()).Add(10, 20));
    Console.WriteLine((new Sample()).Add(10, 20));
}

.NET CodeReflect

private static void Main(string[] args)
{
    Console.WriteLine(new ConsoleApplication6.Sample().Add(10, 20));
    Console.WriteLine(new ConsoleApplication6.Sample().Add(10, 20));
}

.NET Reflector 8

private static void Main(string[] args)
{
    ISample sample = new Sample();
    Console.WriteLine(sample.Add(10, 20));
    ISample2 sample2 = new Sample();
    Console.WriteLine(sample2.Add(10, 20));
}

If you look into the decompiled code, only ILSpy and .NET Reflector gives compilable code. It doesn’t mean other decompilers are not good, but for this given scenario, all the other three decompilers failed reverse engineer C# code properly.

Happy Programming :)

CreateObject equivalent for C#

In current project, I had to use some 3rd party APIs, which is exposed via COM Interop. I found some VB.Net code to consume, but I couldn’t find in C# implementation for the same. Here is the code snippet which is equivalent VB.Net CreateObject method.

var txt = "HelloWorld";
var type = Type.GetTypeFromProgID("vbscript.regexp");
dynamic vbScriptRegEx = Activator.CreateInstance(type);
vbScriptRegEx.Pattern = "l";
Console.WriteLine(vbScriptRegEx.Replace(txt, "##"));

You may get some other errors, if your platform / platform target is different from the COM object compiled platform.

Serializing .NET dictionary

Recently I had to implement XML Serialization in one of my class, it was deriving from base class, which has a dictionary property and XML Serialization was failing due to that. And here is the code snippet which will help you to serialize a .Net dictionary. It is implemented using IXmlSerializable interface

Here is the Unit Tests (It was TDD implementation :))

[TestClass]
    public class SampleTests
    {
        [TestMethod]
        public void TestSampleCanBeSerialized()
        {
            var sample = new Sample();
            sample.Colors = new Dictionary<int, string>();
            sample.Colors.Add(1, "Red");
            sample.Colors.Add(2, "Blue");
            Serialize(sample);
        }

        [TestMethod]
        public void TestSampleIsProperlySerialized()
        {
            var sample = new Sample();
            sample.Colors = new Dictionary<int, string>();
            sample.Colors.Add(1, "Red");
            sample.Colors.Add(2, "Blue");
            var result = Serialize(sample);            
            Assert.IsNotNull(result);
            var newsample = DeSerialize(result);

            Assert.IsNotNull(newsample,"Sample not created");
            Assert.IsNotNull(newsample.Colors,"Couldn't create colors");

            Assert.AreEqual(2, newsample.Colors.Count);
        }

        private static string Serialize(Sample sample)
        {
            using (var stringWriter = new StringWriter())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Sample));
                xmlSerializer.Serialize(stringWriter, sample);
                return stringWriter.ToString();
            }
        }

        private static Sample DeSerialize(string text)
        {
            using (var stringReader = new StringReader(text))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Sample));
                return xmlSerializer.Deserialize(stringReader) as Sample;
            }
        }

    }
}

Here is the actual implementation.

public class Sample : IXmlSerializable
{
    public Dictionary<int, string> Colors { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        var xmlDocument = new XmlDocument();
        xmlDocument.Load(reader);
        var colors = xmlDocument.SelectNodes("//Color");
        Colors = new Dictionary<int, string>();
        foreach (XmlNode color in colors)
        {
            Colors.Add(int.Parse(color.Attributes["Key"].Value.ToString()), color.Attributes["Value"].Value.ToString());
        }
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("Sample");
        writer.WriteStartElement("Colors");
        foreach (var color in Colors)
        {
            writer.WriteStartElement("Color");
            writer.WriteAttributeString("Key", color.Key.ToString());
            writer.WriteAttributeString("Value", color.Value);
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

Happy Programming :)