New C# 6.0 features

As part of the Connect(); event, Microsoft introduced VS2015 Preview, which includes C# 6.0 with few more features. (These features are not included in my earlier post What is new in C# 6.0, as I already mentioned these features introduced by Microsoft in the Connect(); event few days back.)

  • nameof operator – nameof operator allows developers to use program elements as text. In MVVM project, you are using property notifications, it is recommended to use strongly typed property notifications, instead of string. Because you are hard coding the property name, if you rename the property, you need to change the string manually. The nameof operator helps you to use the property as the parameter.
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName != value)
            {
                _firstName = value;
                OnPropertyChanged(nameof(FirstName));
            }
        }
    }
    

    Runtime will replace the property with the property name while generating the IL code.

    IL code generated for nameof operator

    IL code generated for nameof operator

  • null conditional dot operator – as the name indicates it for null checking. This helps you to make null checking fade into the background.
    static void PrintBook(Book book)
    {
        var name = book.Name;
        var price = book.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    I have a function like this, which will print the name and price of the book. Please note I am not doing any null check, if the book instance is null, it will throw exception. The null conditional dot operator helps to avoid this validation and processing. If you are invoking a property of null object instance, it will return null for that property as well, it won’t throw null reference exception.

    static void PrintBook(Book book)
    {
        var name = book?.Name;
        var price = book?.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    In case of value types, Visual Studio will treat the type of the variable as nullable, if you use null conditional dot operator.

    null conditional dot operator - with value types

    null conditional dot operator – with value types

  • string interpolation – Another cool feature, which will help you to manage string formatting easy. In the current framework, you need use string.Format function, it little complex, you need to put numeric place holders ({n}) and based on the number you need to set the variables. String Interpolation will help developers to use actual variables as placeholders.
    var message = string.Format("Book Name :{0} Price :{1}", name, price);
    

    Can be re-write like this.

    var message = "Book Name :\{name} Price :\{price}";
    

    It supports IntelliSense for the variable names, also variables can be identified with different color.

    String Interpolation - IntelliSense

    String Interpolation – IntelliSense

You can download VS 2015 Preview from here

Happy Coding :)

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.