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

You will need Visual Studio 2012 or higher. (Released September 2012). .NET Framework. 4.5.



1) Asynchronous methods


The async and await keywords provide compiler support for working with the Task Parallel Library (TPL).


  class Program
  {
      static void Main(string[] args)
      {
          var p = new Program();
          p.Run();
      }
  
      void Run()
      {
          var task = CalculatePiAsync();
          task.Wait();
      }
  
      async Task CalculatePiAsync()
      {
          var task = new Task(CalculatePi);
          task.Start();
          await task;
      }
  
      void CalculatePi()
      {
          Thread.Sleep(2000);
      }
  }
  

2) Caller info attributes


Caller info attributes provide information about the caller of a function.


  public void DoTest1()
  {
      LogMessage("hello");
  }
  
  public void LogMessage(string message,
          [CallerMemberName] string memberName = "",
          [CallerFilePath] string sourceFilePath = "",
          [CallerLineNumber] int sourceLineNumber = 0)
  {
      Console.WriteLine("message: " + message);
      Console.WriteLine("");
      Console.WriteLine("CallerMemberName: " + memberName);
      Console.WriteLine("CallerFilePath:   " + sourceFilePath);
      Console.WriteLine("CallerLineNumber: " + sourceLineNumber);
  }
  

  message: hello
  
  CallerMemberName: DoTest1
  CallerFilePath:   C:\...\Test1.cs
  CallerLineNumber: 20
  

You can use [CallerMemberName] to implement INotifyPropertyChanged.


  public event PropertyChangedEventHandler PropertyChanged;
  
  int _count;
  public int Count
  {
      get { return _count; }
      set
      {
          _count = value;
          NotifyPropertyChanged(); // explicit property name "Count" not needed
      }
  }
  
  void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
  {
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
  

Ads by Google


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

© Richard McGrath