0

New to C#, and I am trying to pass Dictionaries with differing Key types to a method:

  1. Dictionary<long, object>
  2. Dictionary<string, object>

Is it possible to make my method signature flexible enough to accept both types?

I tried writing my method to be more generic:

public void methodName(IDictionary<object, object> pDictionary)

But I get the error: Error CS1503 Argument 2: cannot convert from 'System.Collections.Generic.Dictionary<long, object>' to 'System.Collections.Generic.IDictionary<object, object>'

I don't totally understand why I cannot implicitly convert long to object, but I supposed it's because it's contained inside a Dictionary. Am I approaching this problem the wrong way, could it be impossible to write a method signature that can handle Dictionaries with differing Key types?

  • 1
    You could make `methodName` generic in the key type e.g. `public void methodName(IDictionary pDictionary)` but it's not clear how you'd be able to make use of it within the method without an argument of type `TKey`. How is the dictionary accessed within the method? – Lee Apr 01 '21 at 21:54
  • How do you propose that an unboxed `long` should be put into an `object` field? More the point, even if the `string` one: what happens if the function tries to do `pDictionary.Add(new object(), ...);` – Charlieface Apr 01 '21 at 22:18
  • Related: [Why can't a List be stored in a List?](https://stackoverflow.com/q/6557/2791540). Same goes for dictionaries. – John Wu Apr 02 '21 at 01:46

1 Answers1

0

You can use a Generic Method. Your method might look like public void MethodName<TKey, TValue>(IDictionary<TKey, TValue> dictionary). If you need to limit the type arguments, you can use a where constraint (public void Method<T>() where T : IList).

Mason Wells
  • 25
  • 1
  • 8