Skip to content

Instantly share code, notes, and snippets.

@mariusGundersen
Created October 21, 2018 12:55
Show Gist options
  • Save mariusGundersen/07c5787a66bed01121d466d747f8122b to your computer and use it in GitHub Desktop.
Save mariusGundersen/07c5787a66bed01121d466d747f8122b to your computer and use it in GitHub Desktop.
Duct-typed extension methods Example 10
// Example 10: add a tuple
// This is just a dummy class that we can use in the example
public class City
{
public City(string name, int population, string country)
{
Name = name;
Population = population;
Country = country;
}
public string Name { get; }
public int Population { get; }
public string Country { get; }
}
// This is the very specific extension method for adding a city to a list from Example 8
public static void Add(this List<City> list, string name, int population, string country)
=> list.Add(new City(name, population, country));
// We can gather up all the parameters in a tuple
public static void Add(this List<City> list, (string name, int population, string country) city)
=> list.Add(city.name, city.population, city.country);
// Now we have parenthesis, not curly braces
var cities = new List<City>
{
("Chongqing", population: 30_751_600, "China"),
("Shanghai", population: 24_256_800, "China"),
("Delhi", population: 11_034_555, "India"),
("Beijing", population: 21_516_000, "China"),
("Dhaka", population: 14_399_000, "Bangladesh")
};
// Output each item, to see if things work correctly
foreach(var city in cities)
{
Console.WriteLine($"{city.Name}: {city.Population} ({city.Country})");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment