C# - What's new in C# 6.0?

You will need Visual Studio 2015 or higher. (Released July 2015). .NET Framework. 4.6.



1) String interpolation


  var cat = "cat";
  var mat = "mat";
  
  var oldStr1 = String.Format("The {0} sat on the {1}", cat, mat);
  
  var newStr1 = $"The {cat} sat on the {mat}";
  var newStr2 = $"Today is {DateTime.Now:dddd MMM dd}";
  

Replace positional parameters with embedded expressions.

2) Read-only auto properties


  public string Name { get; }
  

A property without a set accessor is read-only.

3) Auto property initializers


  public List<string> Items { get; } = new List<string>();
  

You can set an initial value in the auto property declaration.

4) The null-conditional operator


  var first = person?.FirstName;
  person?.Save();
  

Replace null checks with the null-conditional operator '?.'

5) using static


  using static System.Console;
  
  public static void Main()
  {
      WriteLine("Hello");
  }
  

Import static methods from the System.Console class.

6) Expression-bodied function members


  public override ToString() => "To be or not to be.";
  

Replace a statement block with an expression.

7) nameof Expressions


  void Lookup(int isbn)
  {
      if(isbn == 0)
          throw new ApplicationException(nameof(isbn) + " cannot be null");
      ...
  }
  

Returns the name of a variable, property, or member field.

8) index initializers


  private Dictionary<int, string> systemErrors = new Dictionary<int, string>
  {
      [0] = "Success",
      [2] = "File not found",
      [5] = "Access denied"
  };
  

You can now use index syntax to initialize any object that supports an indexer. E.g. dictionary.

9) Exception filters


  try
  {
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://google.com");
      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
      {
      }
      catch (WebException ex) when (ex.Status == WebExceptionStatus.NameResolutionFailure)
      {
          // Handle dns error
      }
  }
  

Adds precondition testing to exception handling.

10) extension Add() methods in collection initializers


  var personList = new PersonList()
  {
      new Person("John", "Doe"),
      new Person("Jane", "Roe")
  };
  
  // Error: 'PersonList' does not contain a definition for 'Add'
  

You can now initialize a collection that does not implement an Add() method by providing an extension method.


  // Extend class PersonList with method Add (by calling AddPerson)
  public static class PersonExtensions
  {
      public static void Add(this PersonList list, Person person) => list.AddPerson(person);
  }
  

The extension Add method fixes the compile error.

11) await in catch and finally blocks


  private static async void cs_example_await_in_catch_and_finally()
  {
        var hostname = "google.com";
        var dnsTask = DnsResolveAsync(hostname);
        try
        {
            Console.WriteLine("try code");
        }
        finally
        {
            var ip = await dnsTask;
            Console.WriteLine("Hostname resolved to {0}", ip);
        }
  }
  
  private static async Task<IPAddress> DnsResolveAsync(string hostname)
  {
    Console.WriteLine("DnsResolve start");
    var task = Dns.GetHostEntryAsync(hostname);
    await task;
    Console.WriteLine("DnsResolve finish");
    return task.Result.AddressList[0];
  }
  

You can now use await in catch and finally blocks.

  DnsResolve start
  try code
  DnsResolve finish
  Hostname resolved to 172.217.10.46
  

12) Improved overload resolution


Consider the following code:


  public void Main()
  {
      DoSomethingWith(TheMeaningOfLife);
  }
  private void DoSomethingWith(Action a)
  {
      // implementation here
  }
  private void DoSomethingWith(Func<int> f)
  {
      // implementation here
  }
  private int TheMeaningOfLife()
  {
      return 43;
  }
  
Prior to C# 6, this would fail with the error:

  the call is ambiguous between the following methods or properties
  'Print(System.Action)' and 'Print(System.Func<int>)'
  

Improved overload resolution fixes this problem.
The compiler calls the second method.

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath