Skip to content

Instantly share code, notes, and snippets.

@manbeardgames
Created August 6, 2019 17:28
Show Gist options
  • Select an option

  • Save manbeardgames/c983f77a96636196bd00a122804d2b8a to your computer and use it in GitHub Desktop.

Select an option

Save manbeardgames/c983f77a96636196bd00a122804d2b8a to your computer and use it in GitHub Desktop.
A quick example showing the use of multiple Deconstruct method overloads as well as deconstruction while deconstructing.
using System;
public class Program
{
public static void Main()
{
// Create new FooBar instance
FooBar fBar = new FooBar("Test String", 42);
// This will call the Deconstruct(out string, out int, out bool) method of FooBar.
var (foo, bar, isEven) = fBar;
// Output to show results.
Console.WriteLine($"Foo: {foo} -- Bar: {bar} -- Is Even: {isEven}");
Console.ReadLine();
}
}
/// <summary>
/// Simple class used to demonstrate the use of multiple Deconstruct overloads
/// and Deconstructception.
/// </summary>
public class FooBar
{
public string Foo { get; set; }
public int Bar { get; set; }
public FooBar(string foo, int bar)
{
this.Foo = foo;
this.Bar = bar;
}
/// <summary>
/// Deconstructs the FooBar instance
/// </summary>
/// <param name="foo">The Foo</param>
/// <param name="bar">The Bar</param>
public void Deconstruct(out string foo, out int bar)
{
foo = this.Foo;
bar = this.Bar;
}
/// <summary>
/// Deconstructs the FooBar instance and tests if the Bar is even
/// </summary>
/// <remarks>
/// You can have more than one deconstruct method. You can even
/// perform a deconstruct within a deconstruct. Deconstructception.
/// </remarks>
/// <param name="foo">The Foo</param>
/// <param name="bar">The Bar</param>
/// <param name="isEven">Is the Bar even</param>
public void Deconstruct(out string foo, out int bar, out bool isEven)
{
// Call the other deconstruct overload using 'this'
(foo, bar) = this;
// Test if bar is even
isEven = bar % 2 == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment