What is new in C# 6.0

Today I got a chance to look into C# 6.0 features. Thanks to ORTIA(Technology innovation division of Orion India Systems), for providing me the MSDN subscription. :)

  1. Exception filters : Exception filters lets you specify a condition for a catch block. The catch block gets executed only if the condition is satisfied.
    try
    {
        throw new CustomException(10);
    }
    catch (CustomException ex) if (ex.ErrorCode == 10)
    {
        Console.WriteLine("Error code is 10");
    }
    catch (CustomException ex) if (ex.ErrorCode == 20)
    {
        Console.WriteLine("Error code is 20");
    }
    

    The above code will write 10, as the Error code property is set to 10.

  2. Declaration expressions – This feature simply allows you to declare local variable in the middle of an expression.
    string Id = "10";
    int result = 0;
    if(int.TryParse(Id, out result))
    {
        Console.WriteLine(result);
    }
    

    The above code snippet can be re-written as like the following in C# 6.0

    string Id = "10";
    if (int.TryParse(Id, out int result))
    {
        Console.WriteLine(result);
    }
    
  3. using static – This feature allows you to specify a particular type in a using statement after that all static members of that type will be accessible is subsequent code.
    using System.Console;
    
    namespace HelloWorldCS6
    {
        class Program
        {
            static void Main(string[] args)
            {
                WriteLine("Hello C# 6.0");
            }
        }
    }
    
  4. Auto property initializer – With C# 6 initialize auto properties just like a field at declaration place.
    class HelloWorld
    {
        //Initiailizing auto property.
        public string Name { get; set; } = "dotnetthoughts";
        //Readonly autoproperty initialization.
        public bool IsExists { get; } = true;
    }
    
  5. Primary Constructor – This feature helps to capture parameters of primary constructor to fields, in the class for furthur processing. When declaring a primary constructor all other constructors must call the primary constructor using :this().
    class HelloWorld(string name)
    {
        public string Name { get; set; } = name;
    }
    
  6. Dictionary Initializer – C# made the Dictionary more cleaner.
    var dictionary = new Dictionary<int, string>()
    {
        { 10, "A" },
        { 20, "B" }
    };
    

    Can be re-written like this

    var dictionary = new Dictionary<int, string>()
    {
        [10] = "A",
        [20] = "B"
    };
    

Note : These are experimental features, you have to explicitly enable this, otherwise VS2014 will show an error, while compiling like this. – Feature ‘primary constructor’ is only available in ‘experimental’ language version.

Experimental feature error - VS 2014

Experimental feature error – VS 2014

You can do this manually editing the project file.(I didn’t found any option to do this via Visual Studio.) You can open the *.csproj file in your favorite text editor and add the following line.

<LangVersion>experimental</LangVersion>

Now it will be like this

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  <PlatformTarget>AnyCPU</PlatformTarget>
  <DebugSymbols>true</DebugSymbols>
  <DebugType>full</DebugType>
  <Optimize>false</Optimize>
  <OutputPath>bin\Debug\</OutputPath>
  <DefineConstants>DEBUG;TRACE</DefineConstants>
  <ErrorReport>prompt</ErrorReport>
  <WarningLevel>4</WarningLevel>
  <LangVersion>experimental</LangVersion>
</PropertyGroup>

Happy Programming :)

Force .NET application to run in 32bit process

Due to lack of 64 bit version of few COM libararies, we faced a situation to run our AnyCPU application into 32 bit. You can do this either by setting the Platform target or by using the corflags command.

  1. Using Platform target feature. – This is the simple solution, you can change the Platform target settings from Project Properties > Build tab.

    Platform Target settings from Project Properties

    Platform Target settings from Project Properties

    This will cause the compiler to set the 32Bit flag in the CLR header of the corresponding assembly. Every time we run this application no matter on what type of OS it will execute as a 32bit process. But this solution although simple and straight forward was not a viable solution for us since – as mentioned above – we want to have one and only one version of our product. Thus all components of our package have to be compiled with Platform Target set to Any CPU.

    From VS 2011 onwards there is new compiler flag available “Prefer 32-bit”, which will help a .NET application compiled to x86 will fail to run on an ARM Windows system, but an “Any CPU 32-bit preferred” application will run successfully. Also, the “Prefer 32-bit” checkbox is only enabled for .NET 4.5+ executable projects.

  2. Using corflags command – Similar to the above solution, here as well we are setting the CLR header to 32 bit using a tool called corflags – You can find more details about this tool here. To set the 32Bit flag, open the Developer Command prompt, navigate to the directory where your assembly is and use this command.
    CorFlags.exe Sample.exe /32Bit+
    

    You can use this solution as part of the build, so that you can switch to x64 in future, developer don’t need to worry about any platforms.

Happy Programming :)

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 :)