C# 7 Features


In this blog post we will discuss about the Local functions/methods, Ref returns and locals,Expression bodied members,Throw Exception from Expression


Local Methods/Functions



Now we can define local functions inside another.Ya, That's right, C# 7 version provides the ability to call a function which is defined inside another function.

static void Main(string[] args)
 
 {
 
 int localvar = 50;

 //local function defined inside main method

 int LocalFunction(int a)

 {

 return localvar * a;

 }

 Console.WriteLine(LocalFunction(50));

 }        


If we observe the code above, local function with the name "LocalFunction" is defined inside the main method and called by main method itself. This is how we can define a local function to perform a specific operation and return value to the enclosed function (main function in the above case).

Ref returns and locals


As we already know that C# allows to pass variable by reference by using a ref modifier,

now we can return value by reference type too.


public ref int Search(int element, int[] elements)
 {
 
      for (int i = 0; i < elements .Length; i++)
      {
   
           if ( elements [i] == element )
            {
          
              return ref elements[i]; // return the storage location, not the value
          
            }
     
       }
 
      throw new IndexOutOfRangeException($"{nameof(element)} not found");

   }
 

 int[] array = { 12,15,-1,0,10,25,45,23};

 ref int place = ref Search(10, array); // aliases 10's place in the array

 place = 9; // replaces 10 with 9 in the array

 Console.WriteLine(array[4]); // prints 9

Following are the points to note while return value by ref


We can only return refs that are "safe to return": Ones that were passed to you, and ones that point into fields in objects.
Ref locals are initialized to a certain storage location, and cannot be mutated to point to another.

Expression bodied members


Expression bodied members introduced in c# 6.0 version with methods and properties and expanded in C# 7.0 on constructors, destructors, getters & setters. The main purpose is to simplify the syntactical expression

Let’s look at the example to understand how they can be used.
        
            member => expression;

Some of the characteristics of expression bodied members are given below.


They provide clean and clear syntax.
Expression bodied member must have a name, return type and returned expression.

Support for expression body definitions was introduced for methods and property get accessors in C# 6 and was expanded in C# 7.

Expression body definitions can be used with the type members listed in the following table:


Member Support as of..
Method C# 6.0
Constructor C# 7.0
Finalizer C# 7.0
Property Get C# 6.0
Property Set C# 7.0
Indexer C# 7.0



public Customer(string name) => names.TryAdd(id, name); // constructors 
 
 ~Person() => names.TryRemove(id, out _); 
 
 public string Name
  { 

       get => names[id];              // getters
       set => names[id] = value;     // setters

  }
         
Throw Exception from Expression

We can easily throw a custom exception in the middle of the expression.
Just call a method  which does this.but c# 7 allows throw as an expression in certain places.

Look at the below code to understand the concept.
 

class Customer
 {

           public string Name { get; }
       
           public Customer(string name) => Name = name ?? throw new ArgumentNullException(nameof(name));
       
           public string GetFirstName()
           {
          
                var parts = Name.Split(" ");
               
                return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
          
           }

     public string GetLastName() => throw new NotImplementedException();
 
 }
Hope you understand these details.please comment below if you like or have a query.


Thanks

Dotnetcodetree

Comments

Popular posts from this blog

Download Excel File using AJAX in JavaScript

How to Capture Image using web camera in Asp.net and C#.NET / VB.NET

How to Install GIT ?