New Features of C# 6 You May Find Quite Useful

C# version 6 came out with the release of Visual Studio 2015. It includes quite a few useful features for the developers. Here is a list of the ones that will make a day for any developer who has been writing code in C# and using the .NET platform:

Auto-Property Initializers

While previously, if you declare a property and need to initialize it, you’d have to do that in the constructor like this:

public class MyClass
{
...
public string MyProperty { get; set; }
...
public MyClass()
{
    this.MyProperty = "default value";
}
...

You can now do it in a one-liner:

public class MyClass
{
...
public string MyProperty { get; set; } = "default value";
...

You Can Use Lambda Expressions for Methods and Properties

Very simple and intuitive to someone who’s been coding in C# syntax, applied anew:

// Property
public string FullName { get; } => { return this.FirstName + " " + this.LastName; }
...
public int Sum() => {
    int sum = 0;
    foreach (var element in this.Elements) { sum += element; }
    return sum; 
}

Static with Classes in Using Statements

I don’t personally agree this is one of the useful ones, but you be the judge for yourself. You can declare a class as static in a using clause and then use the method without prefixing it with the class name itself:

using static System.Console;
...
WriteLine("This is System.Console.WiteLine()");

NULL Conditionals

This is a great feature that I have extensively used by now. Forget the times when you have to write something like this:

if (person != null && person.Age > 30) 
{
    // do something
}

It is now much easier:

if (person?.Age > 30)
{
    // do something
}

The above much not look like much of a simplifying the code but it certainly makes it easier to read code or write it in something like this:

if (company.GetByBranch("Tampa")?.Employees?.First(e => e.Salary > 30000)?.FirstName == "Gru") { Console.WriteLine("got ya!"); }

String Interpolation

This is one of the best new enhancements in C# ever! Forget about string.Format() now, this doesn’t save lives but saves readability like never before!

Old way:

var logMessage = string.Format("I just encountered this error: {0}.{1}My stack trace is:{1}{2}{1}{1}{3}", ex.Message, Environment.NewLine, ex.StackTrace, ex.Data);

How about this?

var nl = Environment.NewLine;
var logMessage = string.Format("I just encountered this error: {ex.Message}.{nl}My stack trace is:{nl}{ex.StackTrace}{nl}{nl}{ex.Data}");

Doesn’t that read better?

nameof keyword

I have yet to find a use for this, other than may in some logging scenario or using it in reflection, but it is a new feature. If you got a field or property you can get its name as a string by using nameof keyword:

var myNameIs = "luefher";
Console.WriteLine(nameof(myNameIs));

The above code will output the name of myNameIs variable to the output, namely "myNameIs".

New Dictionary Initializer

This, in my opinion, just makes it easier to read - a good touch. Kind of goes towards how some other languages handle it, see for yourself, as I said - nice touch:

var dict =
{
    ["one"] = 1,
    ["two"] = 2
};

Exception Filters

This is certainly useful with so many exceptions that are of the same type and just different messages. I think this works as a temporary solution but something better needs to be done here to distinguish certain exceptions from one another. Take a look at the old way, which I'm sure you're familiar with:

catch (Exception ex)
{
    if (ex.Message.Contains("some message")) 
    {
        // do something
    }
    else if (ex.Message.Contains("some other message")) 
    {
        // do something else
    }
    else 
    {
        // default error handling
    }
}

Now you can do that by filtering messages (or any condition, for that matter) in the catch block itself:

catch (Exception ex) when (ex.Message.Contains("some message"))
{
    // do something
}
catch (Exception ex) when (ex.Message.Contains("some other message"))
{
    // do something else
}
catch
{
    // do something
}

Now, keep in mind that when you implement exception handling this way, just like the old way - you are going top catch down. If you declare a general catch at the very top, you'll never get to your bottom.

await in catch and finally

Personally, I have not had a chance to use these so cannot speak much to it. It appears that this is one of the changes that allows async processing that was rather complicated to implement in C# 5. Do comment below, I'd love to learn more about that.

Hope this was helpful!

This entry was posted in C# and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *