Skip to content

Instantly share code, notes, and snippets.

@maloo
Created March 3, 2022 20:39
Show Gist options
  • Save maloo/d15d6d5a82a231c27ba639c8ca5548d9 to your computer and use it in GitHub Desktop.
Save maloo/d15d6d5a82a231c27ba639c8ca5548d9 to your computer and use it in GitHub Desktop.
Example source generator output to deconstruct tuples from expressions
using System.Data;
var dict = new Dictionary<string, object>() {
{ "name", "Marcus" },
{ "age", 44 },
};
var data = new DataTable();
data.Columns.Add("name", typeof(string));
data.Columns.Add("age", typeof(int));
var row = data.NewRow();
row["name"] = "David";
row["age"] = 30;
{
(string name, int age) = dict.DeconstructNameAge();
Console.WriteLine($"Dict: {name} {age}");
}
{
(string name, int age) = row.DeconstructNameAge();
Console.WriteLine($"Data: {name} {age}ish");
}
Console.ReadKey();
public static class Extensions
{
public static (string, int) DeconstructNameAge(this Dictionary<string, object> dict, string key0 = "name", string key1 = "age")
{
return (Convert.ToString(dict[key0])!, Convert.ToInt32(dict[key1]));
}
public static (string, int) DeconstructNameAge(this DataRow row, string key0 = "name", string key1 = "age")
{
return (Convert.ToString(row[key0])!, Convert.ToInt32(row[key1]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment