Thursday, February 9, 2017

C# 6.0 Auto Property Initializers & NULL Conditional Operator


   Version 6 added great new features for developers. Most of these new features talk for themselves and they don't need that much explanation.



Auto Property Initializers




It doesn't matter which way you pick to initialize this object,  we are going to end up with good amount of code just for initialization. Auto Property Initializers can help us to initialize this object faster with less code.





I have given very simple example here, Auto Property Initializer can be any expression!


NULL Conditional Operator

NullReferenceException might be the most common error we have to deal with. Here is another way to handle NULL objects in C#





By using the new operator (?.) we can rewrite this.
If Product is null, Null Conditional Operator (?.) does not generate NullReferenceException .
Also I used Null Coalescing Operator (??) to return 0 if RetailPrice is null.









No comments:

Post a Comment