C# 6.0: Language features and its internals Part 1

C# have been one of the most evolving language in recent times. It was not more than a couple of years when some of the coolest features were introduced with C# 5.0 and today we have announced the next version of C#. In this post we will try to look deep into these features and try to see what exactly is coming in the new version. I would go deeper than just demonstrating the feature so that you are well acquainted on what exactly you would be getting from these features.

1. Auto Property Initializer
2. Expression bodied Function
3. Static Class Uses
4. String Interpolation

More in Part 2 of the post.


Feature 1 :  Auto Property Initializer

Auto properties are not new to C#. It was there since C# 3.0. The auto properties does not require a backing field to be defined which was done automatically during compilation. So as a coder, you can get a ready-made property without writing much of code. As auto properties does not have backing field exposed, you cannot initialize the backing field during object initialization, rather you have to initialize explicitly in constructors.


    public class AutoPropertyInitialier
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string FullName { get; set; }

        public AutoPropertyInitialier()
        {
            this.FirstName = "Abhishek";
            this.LastName = "Sur";

            this.FullName = this.FirstName + " " + this.LastName;
        }
    }
You can see in the above code block, the FirstName and LastName were Auto - Implemented properties, and both of them were initialized during constructor call, as the backing fields are not exposed for them. Think of a situation when your class is pretty big and you want to introduce a new property, you need to again initialize it inside constructor. This is the pain of the developer.

With C# 6.0, the initialization of auto-implemented properties is damn easy. Take a look into the code below :


    public class AutoPropertyInitializer
    {
        public string FirstName { get; set; } =  "Abhishek";
        public string LastName { get; } = "Sur";

        //public string FullName { get; } = this.FirstName + this.LastName;

        public string FullName { get; }

        public AutoPropertyInitializer()
        {
            this.FullName = this.FirstName + " " + this.LastName;
        }
    }

Here the properties FirstName and LastName were initialized directly after the declaration. You can notice the LastName were intentionally made readonly by not mentioning the setter. The backing field produced for a readonly property is also a readonly variable.

The FullName though is initialized inside constructor as the object initialization works before the constructor call, and hence initialization cannot evaluate "this".

In the above image, the C# representation of actual IL is shown which clearly indicates that the properties do have their backing fields. You can also notice the backing fields for property LastName is defined as readonly. The auto-property initialization is handled very cautiously during compilation and is abstract to you and relieves some of the pain points on writing un-necessary code. 


Feature 2 : Expression bodies functions 

Similar to Auto property initialization, C# 6.0 also comes up with expression bodies functions a long awaited feature. Expression bodied function is also a syntactic sugar implemented in the language which adds the flexibility on how you define member functions. 

Lambda expressions are not new to the language, but you might already know you cannot assign a lambda to a member function if the member function is not defined with a delegate. But if you read my internals to Lamba expression, you already know that for each lambda declaration the compiler creates a backing function body, but that function body cannot be exposed to class level. C# 6.0 enhances the language to allow you to define a member function with lanbda expressions. 



    public class ExpressionBodiedFunction
    {
       
        public string WelcomeMsg(string name) => string.Format("Welcome {0}", name);

        public string HelloMsg => "Abhishek";

        public void Print() => Console.WriteLine(this.HelloMsg);

    }
In the above code block the WelcomeMsg is a member function that takes a string argument and returns a string. As per lambda rules, a lambda which has a return statement does not require a return keyword, hence the WelcomeMsg returns the expression with string.Format.

The second property is HelloMsg which is a property like method where the getter of the property HelloMsg will return the string "Abhishek". Remember, as property is also auto-implemented, the get keyword is also automatically evaluated by the compiler.

The last method "Print" is a void method and hence require a non-returning expression. The Console.WriteLine calls the property HelloMsg to print "Abhishek".

Now how does the compiler handles the lambda now without an explicit declaration of delegates ? Well, the answer is simple. The compiler re-writes the lambda into a full functional method body.

Here the WelcomeMsg, HelloMsg and Print after compilation is just a class level methods. The compiler entirely re-written the class into a strongly typed method bodies.


Feature 3 : Static class uses

The C# language teams identified the developers pain points very well, and implemented the Static class uses in the language. If you are using Static types it is always a nice to have feature in the language such that we can omit the repetitive static method call.

For instance, say I want to print a number of lines on screen, using Console.WriteLine. How about if we don't need to mention Console each line when we call WriteLine ? Static class uses does the same thing. Static class uses also recognize extension methods, hence if say a static class defines extension methods, if you add it, it will automatically recognize the extension methods as well.


    using static System.Console;
    using static System.Linq.Enumerable;

    public class UseStatic
    {
        public void CallMe()
        {

            WriteLine("Hi");

            var range = Range(10, 10);
            var check = range.Where(e => e > 13);
            // Static extension method can 
            // only be called with fulll representation
        }
    }


In the above code the WriteLine is automatically detected as we added the head using static statement. The Range is also declared inside System.Linq.Enumerable which is automatically determined and Where is an extension function. The static uses automatically recognized the extension methods as well.

If you look at the internals of the static uses, the compiler rewrites the static type calls on every occurrences of its method call.

In the actual IL, you can see, the WriteLine is padded with its appropriate type Console and Range is also associated with Enumerable. The re-writing is done by the compiler.

Feature 4 : String Interpolation 

String interpolation is another interesting feature introduced with recent version of C# 6.0. Interpolation is not new with strings. We can do string interpolation using string.Format before, but the problem is the code looks really ugly when using interpolation constructs.

For instance,

string myString = "FullName :" + p.First + " " + p.Last;
string myString = string.Format("FullName : {0} {1}", p.First, p.Last);
Here the first instance, is normal string concatenation. This creates an issue with multiple memory allocation if not string interned. The second statement uses string.Format to format a given string and replaces the {} arguments with the proper arguments as parameter to the method. Now while dealing with multiple occurrences of these kind of string placeholders might look very ugly and unmaintainable and error prone.

C# 6.0 comes with a new technique where the string interpolation can take place in between the strings, or rather than putting numeric placeholders, you can use the actual values.


string myString = $"FullName : {p.First, 5} {p.Last, 20}";
Console.WriteLine(myString);

string my2ndString = $"FullName from EBF = {this.EBF.FullName}";
Console.WriteLine(my2ndString);

Here the string need to be started with a $ sign which indicates that the new kind of string interpolation to occur. The {p.First, 5} will be replaced with the value of p.First aligned to 5 characters.

Now what does the compiler do when these kind of interpolation is encountered. Well, you might be surprised to see, that the string is actually replaced by a call of String.Format during compilation.

So here you can see the actual statement after compilation is nothing but a string.Format call. So string interpolation is also a compiler trick. 


Conclusion

So whatever we have seen in this post are few compiler trick introduced to enhance the language C# 6.0. There are few more features introduced which I will discuss in coming article.

I hope this post comes helpful.

Happy Coding.

Also check Part 2 of this post.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

0 comments:

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!