Bhavya

Code -> Break -> Fix -> Blog


Leave a comment

New Features of C# 6.0

Before getting into the new features of C# 6.0, what I understand is there are no BIG changes but we have many small features which will help us to write cleaner code.

New features of C# 6.0 are:

Getter-Only Auto-Property
using Static Class
Easy Dictionary Initializer
Function/Property with Lambda expression.
Exceptions with Filters
String Interpolation
Null conditional (?.) Operators
nameof Operator

Let me know your thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : Exceptions Filters

Visual Basic & F# allows catch blocks to filter exceptions before actually catching them.

With C# 6.0, a C# developer can do the same.

try
 {
 // Create a web request for an invalid site. 
 var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("invalid site");

// Get the associated response for the above request.
 var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
 myHttpWebResponse.Close();
 }
 catch (WebException webEx) if(webEx.Status==WebExceptionStatus.ProtocolError)
 {
 WriteLine("Protocol Error -> Status Description : {0}", 
 ((HttpWebResponse)webEx.Response).StatusDescription);
 }

In the above code, the catch block will only be executed if the Status is ProtocolError.

Also, with C# 6.0, the developer can use await keyword in catch and finally block.

 catch (WebException webEx) if(webEx.Status==WebExceptionStatus.ProtocolError)
 {
 await LogAsync(webEx.Message);
 }

Let me know your thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : Function & Property with Lambda expression (Expression Body)

Another C# 6.0 feature which simplifies the syntax is the use of Lambda expression with Functions.

Developers commonly overrides the ToString() method of the object class.

 public override string ToString()
 {
 return "\{LastName}, \{FirstName}";
 }

But with C# 6.0, this is made simple with the use of Lambda expression with Function (this can be implemented for any Function not restricted to ToString()).

public override string ToString() => "\{LastName}, \{FirstName}";

The same can also be done for Property.

public string FullName => "\{LastName}, \{FirstName}";

You will notice that return string is not in a familiar format for that I suggest you look at my String interpolation blog.

Let me know you thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : nameof Operator

With the introduction of nameof operator, a developer can reduce the use of string literals for program elements like class, field, property etc.

Say we have a method which checks the Name property and if Name property has any numeric character then the method throws an ArgumentException stating “Name property is invalid.”

 // Code which checks if name holds only alphabets
 // and no numberic characters.
 // If name parameter has numeric characters then
 // throw Argument exception.
 ...
 ...
 catch(ArgumentException)
 {
 WriteLine("Name property is invalid.");
 }

If the developer modifies the Name property to FullName. The compiler will not warn the developer to update the string literal which will end up confusing the end-user or we will have an invalid entry in the log (if the string is used for logging).

With C# 6.0 and nameof operator, this can be avoided.

Console.WriteLine(nameof(FullName) + " property is invalid.");

nameof operator can be really useful when calling the OnPropertyChanged().

Instead of :

 public string FullName
 {
 get
 {
 return fullName;
 }
 set
 {
 fullName = value;
 // Call OnPropertyChanged whenever the property is updated
 OnPropertyChanged("FullName");
 }
 }

the developer can now use the nameof operator

  public string FullName
 {
 get
 {
 return fullName;
 }
 set
 {
 fullName = value;
 // Call OnPropertyChanged whenever the property is updated
 OnPropertyChanged(nameof(FullName));
 }
 }

The nameof operator takes a class, method, field, property or variable and returns a string literal.

Let me know your thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : Null conditional Operator (?.)

Problem : Say we have an Employee class with EmpID, Name & PhoneNo properties.

 internal class Employee
 {
 public int EmpID { get; set; }
 public string Name { get; set; }
 public string PhoneNo { get; set; }
 }

Now if we want to print PhoneNo, we need to have a null check for the employee object as well as for PhoneNo property.

if (employeeObject != null && employeeObject.PhoneNo != null)
 {
 WriteLine(employeeObject.PhoneNo);
}

To avoid these checks C# 6.0 introduces a new operator called Null conditional (?.) operator.

Also known as Elvis operator.

The code is now much simpler with C# 6.0


WriteLine(employee?.PhoneNo ?? "No Phone Number available");

Oh man!!! This will surely reduce lots of null checks statements.

Also, the ?. operator makes working with Events much simpler.

For C# version < 6.0:

if (OnPhoneNoChanged != null)
 {
 OnPhoneNoChanged(this, e);
 }

C# 6.0, makes it simpler

OnPhoneNoChanged?.Invoke(this, e);

Let me know your thoughts.

~BS

Twitter Logo


2 Comments

C# 6.0 : String Interpolation

Using String.Format() can be error-prone and difficult to handle if we have lot of place holders, like,


Console.WriteLine(String.Format("{0} {1} {2}", firstName, middleName, lastName));

It will be helpful if we can eliminate the place-holders and use the values in-place.

This is possible with C# 6.0:


Console.WriteLine("\{firstName} \{middleName} \{lastName}");

The above code will in-turn call the String.Format() and do the needful.

This makes the developer’s life simple.

Let me know your thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : Easy Dictionary Initializer

Below is the code to initialize a Dictionary object for C# version < 6.0:

Dictionary<int, string> employees = new Dictionary<int, string> {
{1, "Gabbar"},
{2, "Langda Tyagi"},
{3, "Mogambo"},
{4, "Kesariya Vilayt"},
{5, "Lotiya Pathan"}
};

But with C# 6.0 the above code can be made simple,

Dictionary<int, string> employees = new Dictionary<int, string>;
{
[1] = "Gabbar",
[2] = "Langda Tyagi",
[3] = "Mogambo",
[4] = "Kesariya Vilayt",
[5] = "Lotiya Pathan"
};

Let me know your thoughts.

~BS