Last active
October 21, 2018 12:53
-
-
Save mariusGundersen/ac2a196fefca9350e74b7b27ba0477ec to your computer and use it in GitHub Desktop.
Duct-typed extension methods Example 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example 8: add a new instance | |
// 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 a very specific extension method for adding a city to a list | |
public static void Add(this List<City> list, string name, int population, string country) | |
=> list.Add(new City(name, population, country)); | |
// now create a list of cities, without writing `new City` | |
var cities = new List<City> | |
{ | |
{ "Chongqing", 30_751_600, "China" }, | |
{ "Shanghai", 24_256_800, "China" }, | |
{ "Delhi", 11_034_555, "India" }, | |
{ "Beijing", 21_516_000, "China" }, | |
{ "Dhaka", 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