The next version of c# contains many useful features.These new features will help us to perform the common tasks and to remove the boilerplate code.
“Using” Statement for static class members
In the prior versions of visual studio whenever we need to use a static member of a class we need to fully qualify the member using the name of the containing class. The using statement was used to import the namespaces only,now we can use using statement with a class to bring the static members of the class in scope.There is no way to bring to the static class members into scope.We can not use the following statement in the prior versions of visual studio
using System.Console;
As Console is a class so we are not able to import it ,it is not recognized by the intellisense.
In visual studio 2015 we can apply the using statement to bring the static members of the class in scope.For example to bring the static members of the Console class in scope we have the following using statement now in c# 6.
using System.Console;
So for accessing the static Write() method we can use the below code.We do not need to qualify the Write method with the Console class and can access it directly unlike the previous versions where we have to qualify the Write() method with the Console class name.
Write("Hello World");
This can be a big convenience specially if we are accessing the static class member multiple times.
Writing functions as expressions
When working with function members,such as methods and properties, many times our method have just a single return statement. For example our method can be returning the details of a person and contains just the return statement.Unfortunately we have to write the complete method body enclosed in the curl braces {} even in such a scenario.
Though lambda expressions allows us to write an expression as the method body but the named method can not contain just the expression as the method body.
Now with c# 6 we can write expressions in place of method body even in the case of named methods.So we can write a method to add two numbers using the below expression syntax.
public static int Add(int a, int b) => a + b;
The => above is called the lambda arrow and the right hand side is the function expression .
If we call the above method and pass the arguments as 2 and 3 we get the result 5 as expected.
Console.WriteLine(Add(2, 3));
Auto properties
Read only auto properties
While using auto properties we have to provide both the set and the get accessor otherwise we get a compile time error.If we declare the below auto property in the prior versions of c# we get a compile error complaining that both set and get accessor are required in an auto property.
public string Name { get; }
Now we can declare an auto property which has just the get accessor. Behind the scenes the backing of the auto property is declared as readonly.
Auto properties can be initialized
Other nice feature of auto properties in C# 6 is that we can assign a value directly to the auto property at the time of declaration.This is similar to how we initialize a variable.
public string Address { get; set; } = "Address1";
String Interpolation
To format the strings we usually rely on the String.Format method.To format a string we use the format method as
String.Format("Current date is {0} and time is {1}", DateTime.Now.ToShortDateString(), DateTime.Now.TimeOfDay);
To use the Format method we declare the placeholders in the string and then supply the arguments to the Format method in the same sequence as the placeholders.This is not much intuitive as we have to match the sequence of the placeholders with the sequence of the arguments.Now instead of declaring placeholders in the string and then supplying the values of the placeholders using the arguments we can directly insert the value in the placeholders itself.So we can write the above statement in c# 6 as
Console.WriteLine("Current date is {DateTime.Now.ToShortDateString()} and time is {DateTime.Now.TimeOfDay}");
Null Conditional Operator
Many times we need to access the value of an object property but as a safe check we also need to test if the object is not null.So mostly we use the code as below to check if the object itself is null or not.
//check and assign department and phone number
if ((emp!= null && emp.Department == "HR") && (emp!= null && emp.PhoneNumber == "022-1232222")) { Department = emp.Department; PhoneNumber = emp.PhoneNumber; }
If we don’t check the null values above we will get null reference exception.
Though this is a very common check to prevent runtime exceptions but we have to write the same code whenever we need to access property value.This is boilerplate code which we have to use and it would have been nice if there was a common way to perform the null check.
The good news is now in c# 6 we have the null operator which do the same check as above but using a streamlined syntax.So to access a property value we can use the null conditional operator and the null value will be checked implicitly.We can write the above code using null conditional operator as
if ( (emp?.Department == "HR") && (emp?.PhoneNumber == "022-1232222")) { Department = emp.Department; PhoneNumber = emp.PhoneNumber;
}
nameof operator
Many times we need to fetch the name of the code element such as the name of the method in which exception has occurred.So the usual approach is to pass the name of the code element as a string.For example to pass the name of the method to the ArgumentException() method to report the method in which the error has occurred we have to hardcode the name of the containing method.
So we pass the method name as a string
public void EmployeeDetails() { throw new ArgumentException("EmployeeDetails"); }
The above code appears just perfect as our intent is to pass the method name as a string and that is what we are doing.But if tomorrow we are required to change the name of the method as a part of code refactoring.It’s very likely that the name of the method that we are passing to the ArgumentException() method may be left as such and will refer to the previous name of the method.
To avoid such problems we can use the nameof operator which returns the name of the program element.
public void EmployeeDetails() { throw new ArgumentException(nameof(EmployeeDetails)); }
On calling the above method we get the exception as expected.On viewing the exception details we can see that the name of the message property is the method name which we are passing to the ArgumentException object.
So now even if the name of the method is changed nameof operator will ensure that the new method name is passed to the method.Since the argument to nameof operator is the name of the method instead of hardcoded string so only a valid existing method name can be passed to the nameof operator.
Parameterless constructor in Structure
Now we can declare a parameterless constructor in a Structure.This is use usefull if we need to provide default values to Struct members which are different from the default values for the member datatypes.
struct Employee { public string Department { get; set; } public string BaseLocation { get; set; } public Employee() { Department= "DefaultDepartment"; BaseLocation= "BaseLocation"; } }
So if want to initialize the new Employee variables with some default value we can provide the default values in the constrcutor.If we need to create many instances of the Employee struct then by default the struct fields will have the values which we have provided instead of setting the values on all the struct member variables.
Anonymous says
I believe that is one of the most vital info for me.
And i’m satisfied studying your article. However should observation on few common issues, The web site taste is wonderful, the articles is in reality great :
D. Good process, cheers