Sunday, 14 May 2017

Auto-Property enhancements in C#

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property.
When you declare a property the compiler creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors.
The syntax for automatically implemented properties
1
2
3
//Auto-Property enhancements
public string FirstName { get; set; }
public string LastName { get; set; }
C# 6.0 improves the auto-properties capabilities.
Auto-Property Initializers
Firstly, you can initialize auto-implemented properties similarly to fields. It allows you to declare the initial value for an auto-property as part of the property declaration.
1
2
    // Auto Property Initialization
public string FirstNameInitialization { get; set; } = "Name";
Read-only auto-properties
Read-only auto-properties provide a more concise syntax to create immutable types.
1
2
3
// Read Only Auto Property
public string ReadOnlyFirstName { get; private set; }
public string ReadOnlyLastName { get; private set; }
Read-only auto-properties enable true read-only behavior. You declare the auto-property with only a get accessor:
1
2
3
// True Read-only behavior
public string TrueReadOnlyFirstName { get; }
public string TrueReadOnlyLastName { get; }
Please refer code sample on GitHub

String Interpolation in C#

An interpolated string looks like a template string that contains interpolated expressions. An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations.The arguments of an interpolated string are easier to understand
1
2
3
public string Message { get; set; } = "Message";
//Interpolated Strings
public void WriteMessage() => Console.WriteLine($"Message is {Message} ");
we can use interpolated string anywhere we can use a string literal.
If the interpolated string contains special characters, such as the quotation mark (“), colon (:), or comma (,), they should be escaped.
1
public void WriteMessageEx1() => Console.WriteLine($"Message is \"important\" {Message} ");
if they are language elements they should be included in an expression delimited by parentheses.
1
public void WriteMessageEx2() => Console.WriteLine($"Message is {(string.IsNullOrWhiteSpace(Message) ? "empty" : "Not empty")} ");