Exploring C# 6

With the new version of the framework, and Visual Studio landing .NET world has also been graced with some really cool new features for C#. The new C# 6, while not bringing any new major changes or updates to the language, bring a series of really cool new features to the language, that will specially reduce a lot of boilerplate code.

Because .NET now has a new compiler Roslyn, which is open source! You can now check the new goodness straight from the mouth of the beast in here.

Some of my favourites:

//
//this
public class Book
{
	public string Name { get; set; }

	public Book() {
		Name = "Unkown";
	}
}

//
//can be re-written as this
public class Book
{
	public string Name { get; set; } = "Unkown";

	//even cooler you do this to make read-only fields !
	public int REF { get; }  = "123456";
}
//now image how cleaner the code would look if there were 14 of theses props in you class.

Who doesn’t love lambda expressions? Now you can their syntax in as a body’s method.

//
//this
public bool IsAwesome() { return true; }
public int Sum( int A, int B) { return A + B; }
public void Log( string msg ) { Console.WriteLine(msg); }

//
//can be this
public bool IsAwesome() => true;
public int Sum( int A, int B ) => ( A + B );
public void Log( string msg) => Console.WriteLine( msg );


//
//works in props too
public string FullName { get { return String.Format("{0} {1}", FirstName, LastName); } };

//
//becomes this
public string FullName => String.Format("{0} {1}", FirstName, LastName);

String interpolation in some cases are now nicer as well.

//
//The example above
public string FullName => String.Format("{0} {1}", FirstName, LastName);

//
//Can now be done like this
String.Format($"{FirstName} {LastName}");  

//
//this
string msg = String.format("Super mega ukelele id: {0}", id)

//
//to this
string msg = $"Super mega ukelele id: {id}";

And for last, arguably my favourite one. If you have to do a lot of null checking, you will agree with me.



//
//this 
return ( person != null && person.Details != null ? person.LastName : null )

//
//can be done like this
return person?.Details?.lastName;

//
//another example
var userStateId =
	user == null ? null :
		(user.CurrentStatus == null ? null : 
		  (user.CurrentStatus.GetState() == null ? null :
		    user.CurrentStatus.GetState().id));

//
//this mess can be re-written like so.
var userStateId = user?.CurrentStatus?.GetState()?.id;




Go back.