Deconstructing is unpacking types into single pieces; for instance, a tuple into its items or a class into its properties.
Let's learn more about this process by looking at the following code examples.
// declare a tuplevarbook=("C-Sharp Basics","Jon Doe",1.99);// now we can destruct the tuples into individual itemsvar(title,author,price)=book;// use them like variablesConsole.WriteLine($"Title: {title}");Console.WriteLine($"Author: {author}");Console.WriteLine($"Price: {price}");// declare a dictionary objectvarbooks=newDictionary<string,string>{{"Book One","Author One"},{"Book Two","Author Two"},};// unpack each item into a key/value pair (title/author pair) and loop throughforeach((stringk,stringv)inbooks){Console.WriteLine($"\"{k}\" written by {v}");}We need to implement the Deconstruct method. We can have multiple implementation of this method by overloading.
// declare a class with Deconstruct method(s)classMyBook{publicintId{get;set;}publicstringTitle{get;set;}publicstringAuthor{get;set;}publicMyBook(intid,stringtitle,stringauthor){Id=id;Title=title;Author=author;}// must have the "out" modifier with each parampublicvoidDeconstruct(outintid,outstringtitle,outstringauthor){id=Id;title=Title;author=Author;}// must have the "out" modifier with each parampublicvoidDeconstruct(outstringtitle,outstringauthor){title=Title;author=Author;}}Let's use the MyBook class
// instantiate the "MyBook" classvarmybook=newMyBook(1,"CSharp Bacis","Jon Doe");// deconstruct class properties into a collection of variablesvar(myBookTitle,myBookAuthor)=mybook;// use the variables as neededConsole.WriteLine($"\"{myBookTitle}\" by {myBookAuthor}");// define a record called "Person" with the propspublicrecordPerson(stringFirstName,stringLastName);// instantitate a Person recordvarperson=newPerson("Jon","Doe");var(firstName,lastName)=person;Console.WriteLine($"My name is {firstName}{lastName}");// implemeted an extension methodpublicstaticvoidDeconstruct(thisDateTimeOffsetdate,outintday,outintmonth,outintyear)=>(day,month,year)=(date.Day,date.Month,date.Year);// now instantitate DateTimeOffsetvardate=newDateTimeOffset(2022,9,17,0,0,0,0,TimeSpan.Zero);// deconstruct DateTimeOffset objcet(intday,intmonth,intyear)=date;Console.WriteLine($"I wrote this example on: {month}/{day}/{year}");