How to call static class method from string?

  • A+
Category:Languages

Excuse my ignorance/mistake as I'm a newbie and learning. I have a static class with the name of the country, Finland, as seen below.

namespace Countries {     public static class Finland     {         public static int ID { get; set; } = 7;         public static string nameOfCountry { get; set; } = "Finland";         public static string abbreviation { get; set; } = "FI";         public static string flagLocation { get; set; } = "finishFlag.png";         public static string GetFlag()         {             return "finishFlag.png";         }     } } 

I'm using HttpClient to do GET request a JSON string from a website. Then I use DeserializeObject to deserialize JSON to an object. One of the variables of the object is string countryName (which exactly matches the string, nameOfCountry). By using this string (countryName), I want to call the GetFlag() method from the respective country class. However, I don't know how to call this static method from the string countryName. I can compare nameOfCountry string in with the countryName string, however I have 24 country classes like the class Finland which means 24 if else if statements.

I saw the Type.GetType() method from one of the answers in StackOverflow but I didn't understand how this can be used here as I'm not creating a instance. Please provide an example to solution so that it's easier to understand. Thank you.

 


You don't need 24 different classes, you need 1 class with 24 instances.

public class Country {     public int ID { get; }     public string NameOfCountry { get; }     public string Abbreviation { get; }     public string FlagLocation { get; }      public Country(int id, string nameOfCountry, string abbreviation, string flagLocation)     {         ID = id;         NameOfCountry = nameOfCountry;         Abbreviation = abbreviation;         FlagLocation = flagLocation;     }         } 

Notice that if those properties were static as in the question, all instances would share the value, which is something you don't want here.

The best way to store these classes (assuming you cannot use a database) would be to use a Dictionary:

private static Dictionary<string, Country> _countries = new Dictionary<string, Country> {     ["Finland"] = new Country(7, "Finland", "FI", "finishFlag.png"),     ["USA"] = ... }; 

You can then access these countries by their name:

Country country = _countries["Finland"]; 

Adding countries to the dictionary is then much easier than creating a new class and adding a new if case.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: