Home > front end >  C# dictionary: Outputting all associated object attribute values from a dictionary key
C# dictionary: Outputting all associated object attribute values from a dictionary key

Time:02-18

I have a simple class called Country

 class Country
{
    private string name;
    private string capital;
    private string currency;
    private int gdp;

    public Country(string n, string cap, string curr, int the_gdp)
    {
        name = n;
        capital = cap;
        currency = curr;
        GDP = the_gdp;
    }

    public string Name { set; get; }
    public string Capital { set; get; }
    public string Currency { set; get; }
    public int GDP { set; get; }
}

}

Here is a my dictionary where I have added all the Country objects:

 Dictionary<string, Country> dictCountries = new Dictionary<string, Country>();
        dictCountries.Add("France", new Country("France", "Paris", "Euro", 456));
        dictCountries.Add("Germany", new Country("Germany", "Berlin", "Euro", 789));

        Console.WriteLine(dictCountries["France"]);   

I expected all values associated with the key to be output. However, it outputs just the namespace.class ie. SimpleDictionaryProgram.Country

Why am I not seeing "Paris - Euro - 456" output?

thank you

CodePudding user response:

The Country class is inheriting its ToString method from object, which simply outputs the name of the type. You can override the ToString method in the Country class:

public override string ToString() {
    return $"{capital} - {currency} - {gdp}";
}
Console.WriteLine(dictCountries["France"]);
// Outputs "Paris - Euro - 456"

CodePudding user response:

Because of the base implementation of the ToString function inside the object class which all object are derived from.

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.

Follow the following link to override the function with what you want to print: https://docs.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-6.0#overriding-the-objecttostring-method

public override string ToString()
{
      return Name   ": "   Capital   ": "   Currency   ": "   GDP;
}
  • Related