1

Why can't I do something like this:

var myDictionary = new Dictionary<string, Type>();

// Add data to dictionary

foreach(var kvPair in myDictionary)
{
    var result = SomeMethod<kvPair.Value>(kvPair.Key); // Error
}

So I cannot use the Type that I have in the Dictionary element and use it in the type parameter. Yes I could just send the dictionary to the SomeMethod(KeyValuePair). However I do not have control of how the function is implemented.

Error: The type or namespace name 'kvPair' could not be found (are you missing a using directive or an assembly reference?

I feel like I am missing something pretty foundational and I am not sure what it is.

Schanckopotamus
  • 781
  • 2
  • 6
  • 20
  • @JasonP While that's one possible solution, I think it's a stretch to call it a duplicate since generics aren't mentioned in the question at all. – D Stanley Nov 03 '14 at 19:26
  • @JasonP I'm with DStanley. You could otherwise infer it as *Why this doesn't work?* Just the explanation of why it doesn't work, which is missing in the suggested duplicate. That's not a duplicate, but related question. – Sriram Sakthivel Nov 03 '14 at 19:38

1 Answers1

3

I feel like I am missing something pretty foundational and I am not sure what it is.

Yes, you're missing that generic parameters are static, not dynamic. They are not discoverable at run-time. One option in your case is to use reflection to build the generic method call at run-time:

foreach(var kvPair in myDictionary)
{
    // use reflection to create generic MethodInfo object
    MethodInfo mi = typeof(this).GetMethod("SomeMethod");
    MethodInfo mig = mi.MakeGenericMethod(kvPair.Value);

    // call generic method
    Object result = mig.Invoke(this, new object[] {kvPair.Key}); 

    // cast to desired return type.
}

Before going down that road, however, I would take a step back and see if generics are the best design now you know that they aren't late-bound.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Ahh this makes a lot of sense now. Hmmm ... I like the solution, its interesting, but idk if I want to use reflection to accomplish this. I'll Have to do some more thinking about what I am trying to do. Thanks! – Schanckopotamus Nov 03 '14 at 19:32