what are the new features in C# 6.0. Best Dot Net Training

what are the new features in C# 6.0? Best Dot Net Training

Agenda: New Features of C# 6.0

  1. String Interpolation
  2. Null Conditional Operator
  3. Auto Property Initializer
  4. Dictionary / Index Initializer
  5. Expression-bodied function members
  6. Static Using
  7. name of Expression
  8. Exception Filters
  9. Declaration Expressions
  10. await in catch and finally block

String interpolation

It’s a feature which can eradicate the use of String. Format method which at times becomes little confusing.

 class Person {

              public string Name;public int Age;

}

class Program

{

               static void Main()

             {

                    Person p = new Person() { Name = “Abcd”, Age =25 };

                    var s = String.Format(“{0} is {1} year(s) old”, p.Name, p.Age);

                   Console.WriteLine(s);

                    var s1 = $”{p.Name} is {p.Age} year(s) old”;

                    Console.WriteLine(s1);

                }

}

Null Conditional Operator (?.) :

If the object invoking the method or accessing the property is null, then the operator results in null expression.

static void Main(string[] args)

{

         string s = null;

         s = Trucate(s, 2);

         Console.WriteLine(s);}

         static string Trucate(string s, int len)

         {

            /*if (s != null)

             return s.Substring(0, len); return null;*/

              return s?.Substring(0, len);

         }

}

Auto-property Initializer

This feature enables you to set the values of properties right at the place where they are declared. In the earlier versions of C# we had to often use default constructors to set default values to the properties in the class.

class Person{

      //public Person()

      //{

          //    Name = “John”;

          //    Age = 25;

       //}

       public string Name { get; set; } = “John”; public int Age { get; set; } = 25;

 }

   class Program

  {

     static void Main(string[] args)

    {

       Person p = new Person();

       Console.WriteLine(p.Name + ” “ + p.Age);

    }

}

 

Dictionary / Index initializers

Dictionary / Index initializers allow you to set values to keys through any indexer that the new object has

Dictionary<string, string> capitals = new Dictionary<string, string>(){

     [“USA”] = “Washington DC”,

     [“England”] = “London”,

     [“India”] = “New Delhi”

    };

   var numbers = new Dictionary<int, string>

  {

     [7] = “seven”,

     [9] = “nine”,

     [13] = “thirteen”

 };

 

Expression-bodied function members

Methods, as well as user-defined operators and conversions, can be given an expression body by use of the “lambda arrow”:

class Point {

 public int x, y;     public Point(int a,int b)

   {

         x = a; y = b;

   }

    public Point Move(int dx, int dy) => new Point(x + dx, y + dy);

 }

public static Complex operator +(Complex a, Complex b) => a.Add(b); public static implicit operator string(Person p) => p.FirstName + ” ” + p.LastName;

The effect is exactly the same as if the methods had had a block body with a single return statement. For void-returning methods – the arrow syntax still applies, but the expression following the arrow must be a statement expression:

public void Print() => Console.WriteLine(FirstName + ” ” + LastName);

 

Using static

The feature allows all the accessible static members of a type to be imported, making them available without qualification in subsequent code:

using static System.Console;
using static System.Math;

using static System.DayOfWeek;class Program

{

       static void Main()

       {

             WriteLine(Sqrt + 4 * 4));

              WriteLine(Friday, Monday);

       }

}

name of Expressions

Occasionally you need to provide a string that names some program element: when throwing an

ArgumentNullException you want to name the guilty argument; when raising a PropertyChanged event you want to name the property that changed, etc.

 

Using string literals for this purpose is simple, but error-prone. You may spell it wrong. name of expressions are essentially a fancy kind of string literal where the compiler checks that you have something of the given name, and Visual Studio knows what it refers to so navigation and refactoring will work:

  • If the parenthesized expression evaluates to true, the catch block is run, otherwise, the exception keeps going.
  • Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.
  • It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:
static void Foo(object param1, object param2)
{if (param1 == null)throw new ArgumentNullException(); if (param2 == null)throw new ArgumentNullException();// }

await in catch and finally blocks:

In C# 5 doesn’t allow the await keyword in catch and finally, blocks and developers had to look for work around.

Now in C# 6 figured this issue is resolved and following an example.

static async void AwaitInCatchAndFinallyDemo()
{ FileStream fs = new FileStream(“src.txt”, FileMode.Open);     try {        MemoryStream ms = new MemoryStream();         await fs.CopyToAsync(ms); }  catch (IOException)  {        await fs.FlushAsync();

}  

   finally

{

        byte[] buffer = new byte[10]; 

        await fs.WriteAsync(buffer, 0, 10); 

        if (fs != null)    

         fs.Close();

}

}


SandeepSoni

Mr. Sandeep Soni, CEO & Founder of Deccansoft Software Services. He has over 21years of Experience in Teaching and Development using Microsoft Technologies. Since 1997, of the total 100000+ students, Deccansoft has trained, he has personally trained over 60,000+ students and we are proud of him because almost every student he had trained is very happy with the quality and many are well placed in various I.T Firms. This will reflect in testimonials on our website.

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *