C# 6 has got nothing major coming like LINQ or async/await in past instead it has got several small enhancements which actually helps you clean up your code and get ride of boilerplate code. In this post, I am going to share some of the code snippets I wrote to explore new features in C# 6.
This post is written using VS 2015 CTP6, so the actual specs may vary by the time of final release. If you want to quickly get hands on Visual Studio 2015 CTPs without setting up environment, you can create virtual machine from gallery in Azure
String interpolation:
Methods like string.Format in C# provides great functionality to construct strings using placeholders. However that approach is a bit confusing and error-prone. C# 6 introduces a new way to use variable placeholders directly in string instead of number based placeholders by placing ‘$’ symbol before the string. This makes code a lot more readable.
[csharp]
public static void StringInterpolationEnhancements()
{
string name = "Adil";
DateTime date = new DateTime(2015, 03, 13, 10, 15, 0);
int versionYear = 2015;
// Previously in C# 5
WriteLine(string.Format("This code was written by {0} on {1} using Visual Studio {2}", name, date, versionYear));
// In C# 6
WriteLine(string.Format($"This code was written by {name} on {date} using Visual Studio {versionYear}"));
// In fact you don’t need to call string.format
WriteLine($"This code was written by {name} on {date} using Visual Studio {versionYear}");
// This is especially handy when you add more parameters in string format over the time and the order get confusing
string content = "blog";
WriteLine(string.Format("This {3} was written by {0} on {1} using Visual Studio {2}", name, date, versionYear, content));
WriteLine($"This {content} was written by {name} on {date} using Visual Studio {versionYear}");
}
[/csharp]
Using static members:
A lot of time you have a class with bunch of static methods and you have to call them via class. e.g.
[csharp]
using static System.Console;
//Previously in C# 5
Console.WriteLine("This is how to use static classes");
// In C# 6 by adding namespace using static System.Console;
WriteLine("Just call the static method directly");
[/csharp]
This was one of the feature I liked in Java and its now added in C# as well although Java don’t have many other goodies from C#.
Null propagation:
This one is interesting. Often we have methods with more statements to do null checks then actually intent of method. C# 6 introduces a new null propagation operator (?.) This would automatically check if the left hand side is not null then it uses property of that object.
[csharp]
public void DisplayStudent(Student student)
{
// Previously in C# 5
if (student != null)
{
WriteLine(student.Name);
}
}
public void DisplayStudentInCSharp6(Student student)
{
//In C# 6
WriteLine(student?.Name);
}
[/csharp]
If you want to work with primitive type because C# already has nullable primitives, you can write something like
[csharp]
int? age = student?.Age;
[/csharp]
This is especially handy in firing events because you don’t have to do a thread safe null check
[csharp]
event EventHandler OnNetworkChange;
void RaiseNetworkChange()
{
OnNetworkChange?.Invoke(this, new EventArgs());
}
[/csharp]
However I was looking for cases when we have to add null checks before iterating on a collection but I don’t think it works in foreach statement but may be it’s good idea to check language specs or ask this question to language team. Do you know about it, reader?
[csharp]
// can I say something like student?.Courses?.GetEnumberable()
foreach (var course in student.Courses)
{
WriteLine(course.Id);
}
[/csharp]
Expression bodied members:
For method having single return statement or properties with a getter having single return statement, C#6 lets you implement a method with single expression, like we use to do define lamba expressions.
[csharp]
//Instead of
public override string ToString()
{
return string.Format("Value : {0}, value};
}
// We can define expression in C# 6
public override string ToString() => $"Value : {value}";[/csharp]
Dictionary Initializers:
C# 3.0 introduces concept of object intializers where you can initialize properties of object like
[csharp]Student student = new Student { Name = "Adil" };[/csharp]
However if you want to initialize index or dictionary you have to initialize say dictionary first and set value at index in separate statement but not any more
[csharp]Dictionary<string, int> dictionary = new Dictionary<string, int> {["Year"] = 2015,["Month"] = 03,["Day"] = 15 };[/csharp]
Other enhancements:
There are few other enhancements in the language as well.
– Getter only auto properties
– Constructor assignment for getter only properties
– Auto properties initializers
– Catching exception with filters
– await in catch/finally block
– nameof operator
[csharp]
public class OtherEnhancements
{
// A getter only property with readyonly backing field
public int DemoInt { get; }
// An auto property intialized with default value
public string DemoString { get; set; } = "Demo";
public OtherEnhancements()
{
// Assignment in constructor for getter only field behaves like readonly field
this.DemoInt = 100;
}
public void DemoMethod()
{
try
{
// Some code to capable to raise FileNotFoundException
}
// catch exception with filter to handle only for particular file
catch (System.IO.FileNotFoundException exception) when (exception.FileName == "abc.txt")
{
// In previous version of C#, you have to check it inside
// and then re throw which would result in losing exception data
}
}
}
[/csharp]
That’s all for this post. The complete sample for above code snippets is available at Github Gist.
Have you tried new features yet? any interesting scenario you would like to share in comments?
4 Comments
Muhammad Usama Khalil · April 23, 2015 at 6:15 pm
Great post. wanted to check with you, regarding the below line.
Was this not working in foreach? i think foreach does not throw error if Courses is null, it won’t iterate.
foreach (var course in student?.Courses)
{
WriteLine(course.Id);
}
adilamughal · April 24, 2015 at 10:52 am
No, I was not expecting that but it was giving error
leena deep · July 2, 2015 at 7:39 am
Superb..Its really outstanding and i learn lot.Thanks for sharing this codding…
cloud
computing training in Bangalore
Session: A lap around Visual Studio 2015 – Adil's Tech Weblog · December 28, 2015 at 11:04 pm
[…] Playing with C# 6 features […]