knot22 knot22 - 3 years ago 62
C# Question

a method that takes Dictionary with different data types

The following code goes to a class called Formula and generates numbers and labels for the formula. These come back in 2 separate Dictionarys because the numbers are double data type and the labels are string.

Formula formula = new Formula(formula_type, primary_output, fat_values);

Dictionary<string, double> numbers = formula.generateNumbers();
Dictionary<string, string> labels = formula.generateLabels();


I am trying to create a method that can be fed either of these Dictionarys but am stuck on what to put in as the data type in the method signature (see ??? in code below).

private static void displayData(string text, Dictionary<string, ???> dict)
{
string words = "The " + text + " Dictionary contains the following:";
Console.Out.WriteLine(words);
foreach (var pair in dict)
{
Console.Out.WriteLine(pair.Key + "=>" + pair.Value);
}
Console.Out.WriteLine("");
}


Is there a simple way to accomplish this? If the solution is complex, an alternative approach would be preferable because simplicity is important.

Answer Source

Use a generic method

private static void displayData<T>(string text, Dictionary<string, T> dict)
{
  string words = "The " + text + " Dictionary contains the following:";
  Console.Out.WriteLine(words);
  foreach (var pair in dict)
  {
    Console.Out.WriteLine(pair.Key + "=>" + pair.Value.ToString());
  }
  Console.Out.WriteLine("");
}

To call:

displayData<string>("text",labels);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download