-4
public void Method(Dictionary<any datatype, any datatype> dict)  
{     
    foreach (var o in dict)
    {
        Console.WriteLine(o);
    } 
}

and then when we need to call the Method, we can put any kind of Dictionary there. e.g. Method(new Dictionary< int,string >()); Method(new Dictionary< string, string>()); Can we do that? Also, can we output a dictionary for any kind of data type?

DerStarkeBaer
  • 669
  • 8
  • 28
Alice Guo
  • 35
  • 7

1 Answers1

2

I recommend Generic Methods (C# Programming Guide)

Here's a snippet for your case.

static void Main(string[] args)
{
    // Example dictionary from
    // from https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8
    // Create a new dictionary of strings, with string keys.
    //
    Dictionary<string, string> openWith =
        new Dictionary<string, string>();

    // Add some elements to the dictionary. There are no 
    // duplicate keys, but some of the values are duplicates.
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");

    Print(openWith);
}

static void Print<T, U>(Dictionary<T, U> data)
{
    foreach (var o in data)
    {
        Console.WriteLine(o);
    }
}
tymtam
  • 31,798
  • 8
  • 86
  • 126