What are Deconstructors in C# 7.0?

CsharpServer Side ProgrammingProgramming

C# allows to use multiple deconstructor methods in the same program with the same number of out parameters or the same number and type of out parameters in a different order.

It's a part of the new tuple syntax - which has nothing to do with the Tuple<> classes but is taking from functional programming.

Deconstruct keyword is used for Deconstructors

Example

public class Employee{
   public Employee(string employeename, string firstName, string lastName){
      Employeename = employeename;
      FirstName = firstName;
      LastName = lastName;
   }
   public string Employeename { get; }
   public string FirstName { get; }
   public string LastName { get; }
   public void Deconstruct(out string employeename, out string firstName, out
   string lastName){
      employeename = Employeename;
      firstName = FirstName;
      lastName = LastName;
   }
}
class Program{
   public static void Main(){
      Employee employee = new Employee("emp", "fname", "lname");
      (string EName, string Fname, string Lname) = employee;
      System.Console.WriteLine(EName);
      System.Console.WriteLine(Fname);
      System.Console.WriteLine(Lname);
      Console.ReadLine();
   }
}

Output

emp
fname
lname
raja
Published on 19-Aug-2020 13:46:30
Advertisements