What’s New Features In C# 6.0 By Sagar Jaybhay

List Of All Features In C# 6.0 By Sagar Jaybhay

History Of C#

  • C# version 1.0 was released in 2002 and now in 2019 C# becomes 17 yr’s old.
  • In C# 2.0 in 2005 Generic<T> were added
  • The C# 3.0 in 2007 Linq added and which is awesome
  • C# 4.0 in 2010 Dynamic keyword is added
  • C# 5.0 in 2012 async-await are added
  • In C# 6.0 in Microsoft, more concentrate on rewriting the compiler features rather than adding new features.

Auto Property Initializer

This allows us to initialize the read-only property.

First, we see a read-only property.

public string FirstName { get; }
public string LastName { get;  }

In this, we use only get means we can read only this data we can’t set the value of these properties.

So auto property initializers are.

public ICollection<double> Grades { get; } = new List<double>();

By using this we have true automatic read-only property with auto initiazlization.

The auto property came into existence at C# version 3.0. It is used for code simplification and by using this your code becomes more readable .

One of the great features of c# is you can declare a property.

public class Student
    {
        public Guid Id { get; }=Guid.NewGuid();
    }

In this code, you can initialize the property at the time of declaration.  By using this feature you don’t have a need to write a constructor and initialize the property in that constructor.

In the previous version of c# we not able to write a property only with get.  

read-only property c# 5.0
read-only property c# 5.0
C# 6.0 Property Initialization
C# 6.0 Property Initialization

Why auto-property initialization needed?

Suppose I have a class like below

public class Student
    {
       public string Fname { get; private set; }
    }

I am writing this code because I want my property read-only and I don’t want to set value from outside. But somehow by mistake, I implement one method and changed the value of that Fname field like below which is completely valid.

public class Student
    {
       public string Fname { get; private set; }

       public void ByMistake()
       {
           Fname = "sagar";
       }
    }

To avoid this in C# 6.0 introduced auto property initialization for read-only field and our code become

public class Student
    {
        public string Fname { get; } = "Mr. Sagar Jaybhay";
    }

By using this our field becomes Immutable.

Immutable Property In C# 6.0
Immutable Property In C# 6.0

And if try to change in the class itself it gives the compile-time error.

public class Student
    {
        public string Fname { get; } = "Mr.";

        public void tryToChange()
        {
            Fname = "sagar";
        }
    }

Check below code by that you will able to change read-only property value but it is in the constructor.

public class Student
    {
        public string Fname { get; } = "Mr.";

        public Student()
        {
            Fname = "sagar";
        }

        public void tryToChange()
        {
            Fname = "sagar";
        }
    }
read-only property in constructor initialization
read-only property in constructor initialization

Static using statement / static import

using the static System. Console;

If in our code we use many static classes and every time when we want to call the method we use class-name.method-name so in C# 6.0 we have new feature static import means take an example if we want to print name on console we write it like below.

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Sagar Jaybhay");
        }
    }
}

But if we do the static import our code becomes more readable.

using System;
using static System.Console;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello Sagar Jaybhay");
        }
    }
}

Both will produce same output.

Means C# 6.0 allows you to import static classes and enumerations.

Static Import in C# 6.0
Static Import in C# 6.0

Dictionary Initializer:

In previous versions of .net if we want to initialize the dictionary we use below code. Is c# 3.0 likes syntax.

Dictionary<string,string> _defDictionary=new Dictionary<string, string>()
        {
            { "admin","sagar"},
            { "guest","who"},
        };

But in C# 6.0 it comes up with new syntax which makes sense that we assign the value to the respective key.

Dictionary<string, string> _defDictionary = new Dictionary<string, string>()
        {
            ["admin"] = "Sagar Jaybhay",
            ["Guest"]=  "who"
        };
public class Student
    {
        public Guid Id { get; } = Guid.NewGuid();

        Dictionary<string, string> _defDictionary = new Dictionary<string, string>()
        {
            ["admin"] = "Sagar Jaybhay",
            ["Guest"]=  "who"
        };

    }

By using this it looks like we use it with key-value pair like structure.

Internal Exe Code
Internal Exe Code

nameof operator

This operator obtains the name of variable name, type, and member as a string constant.

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List
Console.WriteLine(nameof(List<int>.Count));  // output: Count
Console.WriteLine(nameof(List<int>.Add));  // output: Add

var numbers = new List<int> { 1, 2, 3 };
Console.WriteLine(nameof(numbers));  // output: numbers
Console.WriteLine(nameof(numbers.Count));  // output: Count
Console.WriteLine(nameof(numbers.Add));  // output: Add

It is useful because it doesn’t have some performance penalty because the value is evaluated at compile time only no need for runtime.

By using this your code becomes more readable and argument checking code more maintainable.

public string Name
{
    get => name;
    set => name = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null");
}

FormattableString class

It represents the composite format string, along with the arguments to be formatted.

What is Composite format string?

It means string consist of fixed text which intermixed with indexed placeholder which also called as format items.

Composite formatting is supported by the following methods

  • String.format
  • Console.writeline
  • StringBuilder.AppendFormat

Instead of using composite format strings, you can use interpolated strings if the language and language version that you’re using support them.

string name = "Sagar";
String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now);

Formatting string operation link: https://docs.microsoft.com/en-us/dotnet/standard/base-types/performing-formatting-operations?view=netframework-4.8

If the interpolated string is casted to FormattableString, the compiler rewrites the interpolated string to create a new FormattableString using FormattableStringFactory.Create

object value1 = "Sagar";
object value2 = "Jaybhay";
var str = $"Test {value1} {value2}";
formatable string in C# 6.0
formatable string in C# 6.0
class Program
    {
        private static string Name = "Sagar";
        private static string SurName = "Jaybhay";

        static void Main(string[] args)
        {
            string oldway = string.Format("Name: {0} ,Surname:{1}", Name, SurName);

            string newWay = $"Name:{Name} , Surname: {SurName}";

            FormattableString newFormattableString = $"Name:{Name}, Surname:{SurName}";
            string invarient = FormattableString.Invariant(newFormattableString);
            Console.Write(invarient);
            Console.Read();
        }
    }

Safe Navigation Operator: also called null conditional operator (?.)

Before C# 6.0

class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }


    class Program
    {
        

        static void Main(string[] args)
        {
            Person p = null;
            if (p != null)
            {
                if(p.FirstName!=null&&p.LastName!=null)
                    Console.WriteLine(p.FirstName+" "+p.LastName);
            }
        }
    }

In above code, we have one class person and in Program class we create object reference and after that we want to print firstname and Lastname of that person so we did the check for null value and then we print it on console.

In c# 6.0 we got much cleaner way to write above lines of code in a single line.

 class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Person p = null;
            Console.WriteLine(p?.FirstName??""+p?.LastName??"");
            Console.Read();
        }
    }
Safe Navigation Operator
Safe Navigation Operator

Exception filters/catch with when the block

When it is a contextual keyword which used to specify filter condition in 2 contexts:

class Program
    {
        private static bool Filter(Exception ex)
        {
            return ex.Message == "exception";
        }

        static void Main(string[] args)
        {

            try
            {
                throw new Exception("exception");
            }
            catch (Exception ex) when(Filter(ex:ex))	
            {
                Console.WriteLine(ex);
                throw;
            }

            Console.Read();
        }
    }

when can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute. Its syntax is

 catch (Exception ex) when(Filter(ex:ex))	

where expr is an expression that evaluates to a Boolean value. If it returns true, the exception handler executes; if false, it does not.

You may also like...

Leave a Reply

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