Skip to main content

10 new features to know about C# 7.0


image source: http://www.c-sharpcorner.com

1. Tuples:  

 Tuples are a temporary grouping of values.A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class.Now with C# 7.0, we can return more than one value from a method.It supports a direct way to return multiple return values from a method.

2) Ref Return and Locals:

C# now supports returning values from methods by reference. In addition, local variables could be declared as ‘ref’ variables. A method could return a reference to an internal data structure. Instead of returning a copy, the return value would be a reference to the internal storage:
ref  PhysicalObject GetPointer(Position p)
 {
 int index = p.GetIndex();
 return ref Objects[index];
 }
 ref var a = ref GetPointer(p);
 a.SomeFunction();

3) Throw Expressions

In C# 7.0 you can throw exceptions directly from expressions. The following example will show you how:
string s = (Age < 58 ? throw new Exception("Not a senior citizen!")) : "Valid User : Senior citizen!!";

4) Expression Bodied Members

Expression-bodies methods, properties can be used in all kind of members.C# 7.0 adds accessors, constructors, and finalizers to the list of things that can have expression bodies:
class Car
 {
         public Car() => Console.WriteLine($"{nameof(Car}");// constructors
  ~Car() =>Console.WriteLine($"destructor{nameof(Car}"); // finalizers
   public string Car
  {
  get => _car;             // getters
  set => _car = value;    // setters
  }
}

5) binary literals

In C# 7.0 you can also write numbers in binary form. See the following code:
 int i = 0b101000;
  MessageBox.Show(i.ToString());
The above code stores number 40 in an integer variable using its binary representation 101000. The prefix of 0b or 0B indicate that its a binary literal. Of course, when you output the value of i it's displayed as 40 and not in it binary format.

6) Out Variables

In C# 7.0 we can define a method's out parameters directly in the method.
 static void Main(string[] args)
 {
 GetBookDetails(out string authorName, out string bookTitle, out long publishedYear);
 Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",
 authorName, bookTitle, publishedYear);
 Console.ReadKey();
 } 
 static void GetBookDetails(out string name, out string title, out long year)
 {
 name = "IIBF";
 title = "Bank Financial Management";
 year = 2001;
 }

7) Deconstruction

While constructing an object you typically pass values to it and then assign those values to the internal members of the class. Deconstruction does exactly opposite. It retrieves values from an object and assigns them to variables. Let's understand this with an example.
Consider the following Employee class :
class Employee
 {
 public int EmployeeID { get; set;}
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public Employee()
 {
 }
 public Employee(int id,string fname,
  string lname)
 {
 this.EmployeeID = id;
 this.FirstName = fname;
 this.LastName = lname;
 }
 public void Deconstruct(out int id,
 out string fname,out string lname)
 {
 id = this.EmployeeID;
 fname = this.FirstName;
 lname = this.LastName;
 }
 }
To see the deconstruction in action you would write:
 private Employee GetEmployee()
 {
   Employee emp = new Employee(1, "Jenny", "James");
   return emp;
 }
 (int id, string fname, string lname) = GetEmployee();
 MessageBox.Show($"{id} - {fname} - {lname}");

8) Pattern matching 

C# 7.0 introduces what is known as pattern matching - a feature that allows you to test a value for certain shape and also extract information form that value.
Is-expressions with patterns :
 object o = true;
 if (o is true)
 {
 Console.WriteLine("yes it's true");    
 }
 object p = 5;
 if (p is int i)
 {
 Console.WriteLine("It's int !!");
 Console.WriteLine(new string('*', i));    
 }
Switch statements with patterns :
C# 7.0, as part of Visual Studio 2017, brings switch statements into the 21st century, thanks to the  new pattern-matching features added to case blocks.
private void ShowData(object param)
 {
 string msg = "";
 switch(param)
 {
 case Employee e:
 msg = $"Employee - {e.FirstName}
  {e.LastName}";
 break;
 case Customer c:
 msg = $"Customer - {c.CustomerID}
   {c.CompanyName}";
 break;
 case Order o:
 msg = $"Order - #{o.OrderID}
    {o.CustomerID} {o.OrderDate}";
 break;
 case null:
 msg = $"Data is null.";
 break;
 default:
 msg = "Unknown data.";
 break;
 }
 MessageBox.Show(msg);
 }
As is clear from the switch statement, you can now use any types in the statement. The individual case clauses uses patterns to test the param against certain type or a constant (Employee, Customer, Order, null etc.). You can access the pattern variables inside the individual case blocks as before.
Remember that with this arrangement the order in which the case clauses appear matters. If some cause meets the pattern further case clauses won't be evaluated.

9) Digital separators

A digital separator allows you to separate digits of any number for the sake of better readability. consider the following example:
 var i = 123456789;
 var j = 123_456_789;
The first line is an ordinary variable declaration. The second line uses a digital separator (the underscore character) to separate digits of a number.
In the older versions of C# numbers could be represented as a decimal or hexadecimal values.

10) Local Functions         

It allows defining and calling a named, inline function inside a function member’s body. Unlike a local variable, which has to be used after being defined, a local function can be called before or after it is defined.As the name suggests a local function is a function that exists locally to another function. It's like a function inside a function. Consider the following Example:
private static void Main(string[] args)
 {
 string FormatStr(string arg)
 {
 return "TestId_"+arg;
 } 
 Console.WriteLine(FormatStr("Employee1"));
 }
 or shorter:
 private static void Main(string[] args)
 {
 string FormatStr(string arg) =>"TestId_"+arg;
 
   Console.WriteLine(FormatStr("Employee1"));
 }



Comments