Click here to Skip to main content
14,358,929 members

C# 6 Overview

Rate this:
4.46 (10 votes)
Please Sign up or sign in to vote.
4.46 (10 votes)
8 Jan 2015CPOL
C# 6 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 cannot use the following statement in the prior versions of Visual Studio:

using System.Console;

As Console is a class, we are not able to import it, it is not recognized by the intellisense.

c#6 import class

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 especially if we are accessing the static class member multiple times.

Expression Bodied Functions

When working with function members such as methods and properties, many times, our method has 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 allow us to write an expression as the method body, but the named method cannot 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; }

c# 6 auto properties

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

Another 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 property itself is not null. So mostly, we use the code as below to check if the property values are 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 for department and phone number above, we will get null reference exception.

Though this is a very common check to prevent runtime exceptions, 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 does the same check as above but using a streamline 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.

Image 3

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 useful 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 constructor. 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.

The post C# 6 Overview appeared first on codecompiled.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

I have a keen interest in technology and software development.I have worked in C#,ASP.NET WebForms,MVC,HTML5 and SQL Server.I try to keep myself updated and learn and implement new technologies.
Please vote if you like my article ,also I would appreciate your suggestions.For more please visit Code Compiled

Comments and Discussions

 
GeneralMy vote of 3 Pin
Sung M Kim8-Jan-15 11:44
professionalSung M Kim8-Jan-15 11:44 
QuestionWrong description of the "null conditional operator" Pin
W. Kleinschmit8-Jan-15 3:25
memberW. Kleinschmit8-Jan-15 3:25 
GeneralMy vote of 3 Pin
Amit Pandey 27-Jan-15 23:55
professionalAmit Pandey 27-Jan-15 23:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Technical Blog
Posted 7 Jan 2015

Tagged as

Stats

15.1K views
7 bookmarked