QA InfoTech » Dot Net » C# 6.0 cool features

C# 6.0 cool features

  1. Auto-Property InitializersIn early version of c# if we want to set a default value for a property in a class, we do this in the constructor. In C# 6.0 using Auto-property initializers we can assign a default value for a property as part of the property declaration itself.

      // Old way

		class Program{  
  			public Program()    {  
   			   MyProperty = 10;   
 			} 
   			public int MyProperty
 			{
 				get; set; 
			}
                }
                // New way                  class Program{  
			  public int MyProperty { get; set; } = 10
                 }

 

 

  2. Using static
	With static members you don't need an instance of an object to
   invoke a method, you just use the typename, a dot, a static method 
   name, and apply parentheses and parameters. This feature allows us 
   to access the static methods inside a class directly without speifying
   its class name. Usually we ue Convert.ToInt32 to convert a value to 
   integer. But using this feature we can just use ToInt32 to convert. 
   // Old way 
    namespace TestApp{
    class Program    { 
       static void Main(string[] args)        {
            var value = Convert.ToInt32("2015");   
     }    }}
	// New way 
	 using Convert; namespace TestApp{ 
  	 class Program    {      
  	 static void Main(string[] args)        {    
       var value = ToInt32("2015");       
 	}    }}

3. Dictionary Initializers 

Ever since C# version 3 came around, we’ve had the ability to initialize collections like lists and dictionaries using the key value pairs are       surrounded with curly braces. With C# 6.0 we can achieve the same result, using key value inside of square brackets and a sign of value using an equal sign.

// Old way

	Dictionary dict = new Dictionary<int, string>{ 
	   {1, "Apple" },
	   {2, "Microsoft" },
	   {3, "IBM" }
	};

// New way

	Dictionary dict = new Dictionary<int, string>{ 
	   [1] = "Apple",    [2] = 	"Microsoft",    [3] = "IBM" 
	};

4. Getter-only auto-properties
When we use auto implemented properties in old vesion of c#, we must provide both get and set. If you want the property value should not be set, you can use the private accessor on the setter, With C# 6.0, you can now omit the set accessor to achieve true readonly auto implemented properties:

// Old way

	public int MyProperty { get; private set; }

// New way

	public int MyProperty { get; }

5. await in catch and finally block

In c# 6.0 the await keyword can be used inside catch or finally block. Usually we would write log when any exception occured inside catch block itself. In those times we no need to wait for that execution to be completed before going to next line of execution. So using the await keyword those execution will be asynchronous.

	Try{ }
	catch (Exception){ 
	   await LogManager.Write(ex);
	}
	finally{ 
	   await LogManager.Write("Done");
	}
	6. Declaration expressions

	Using this feature we can declare local variable in an expression itself instead 
        of declaring globally. But the scope of that variable will be inside the loop.

	// Old way 
	int parsed;if (!int.TryParse("12345", out parsed)){ }

// New way

	if (!int.TryParse("12345", out int parsed)){}
7.String Interpolation

This feature is one of an addition to the string format technique in c#. So far we used 
+ sign or string.format to format a string. But in this feature we can directly use the 
value to be concatinate inside the string itself using \{} symbol. Any condition can be 
used inside the braces.

// Old way 
public string FormatString(int value){
    return "Total # of tickets: "+ value + " tickets";
}
public string FormatString(int value){ 
   return string.Format("Total # of tickets: {0} tickets", value);
}

// New way

public string FormatString(int value){ 
   return "Total # of tickets: \{(value <= 1 ? "ticket" : "tickts")}";
}

// Some more samples,

var s = "\{person.Name} is \{person .Age} year\{(person.Age == 1 ? "" : "s")} old";

8. 12. nameof

Used to obtain the simple (unqualified) string name of a variable, type, or member. When
reporting errors in code instead of hard code it.

// Old way 
public void SaveData(){ 
   try    {    }  
  catch (Exception ex)    {
        this.WriteLog("SaveData", ex);    
}}

// New way

public void SaveData(){ 
   try    {    }   
   catch (Exception ex)    {   
     this.WriteLog(nameof(SaveData), ex);   
 }}

About the Author