How to do it...

  1. If you created the Student class earlier, you should have something similar to this in your code:
        public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public List<int> CourseCodes { get; set; }
}
  1. To create a deconstructor, add a Deconstruct method to your Student class. You will notice that this is a void method that takes two out parameters (in this instance). We then just assign the values of Name and LastName to the out parameters.
If we wanted to deconstruct more values in the Student class, we would pass in more out parameters, one for each value we wanted to deconstruct.
        public void Deconstruct(out string name, out string lastName)
{
name = Name;
lastName = LastName;
}
  1. Your modified Student class should now look as follows:
        public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public List<int> CourseCodes { get; set; }

public void Deconstruct(out string name, out string lastName)
{
name = Name;
lastName = LastName;
}
}
  1. Consuming our Student class (just like we did with Tuples) can now be accomplished as follows:
        Student student = new Student();
student.Name = "Dirk";
student.LastName = "Strauss";

var (FirstName, Surname) = student;
WriteLine($"The student name is {FirstName} {Surname}");
  1. Running the Console Application will display the deconstructed values returned from the Student class.
  1. Deconstructors can just as easily be used in extension methods. This is quite a nice way to extend the existing type to include a deconstruction declaration. To implement this, we need to remove the deconstructor from our Student class. You can just comment it out for now, but essentially this is what we are after:
        public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public List<int> CourseCodes { get; set; }
}
  1. The Student class now does not contain a deconstructor. Head on over to the extension methods class and add the following extension method:
        public static void Deconstruct(this Student student, 
out string firstItem, out string secondItem)
{
firstItem = student.Name;
secondItem = student.LastName;
}
  1. The extension method acts on a Student type only. It follows the same basic implementation of the deconstructor created earlier in the Student class itself. Running the console application again, you will see the same result as before. The only difference is that the code is now using the extension method to deconstruct values in the Student class.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119