Search code examples
c#classsubitem

C# Class with Sub-Items


Let's say, I want to have a main class with many sub-classes in it, the sub classes all with the same properties/methods, and I need to access them in many different other code parts.

Example: Main class: Country

Sub classes / Items: Germany, Netherlands, Great Britian, France, ...

Then defining individual properties for each Country, like Population, Units, ...

So later in code I can access it like

if (Country.France.Units < Country.Germany.Units)
Console.WriteLine("foo");

Edit: Thanks for the answers everyone, CodeCaster's solution is perfect for my purpose. The others are right too, parsing the dictionary by string values is just less work...


Solution

  • You don't want to do this, because then for every country added you'd have to recompile, meaning you can't automatically link data loaded from an external data source to a statically-typed property.

    Use a dictionary instead:

    var countries = new Dictionary<string, Country>();
    
    // ...
    
    if (countries["France"].Units < ...)