Does the dynamic keyword in C# 4 permit certain previously impossible operations with generics?

StackOverflow https://stackoverflow.com/questions/1630729

  •  06-07-2019
  •  | 
  •  

Question

The dynamic keyword in C# 4 introduces new ways to work with objects that weren't previously possible. How does this overlap with generics? Specifically, are there operations that would be potentially useful which are now legal and valid?

For example, this isn't possible now:

// Use a type whose value is known only at runtime.
Type t = ...;
List<t> l = new List<t>();
// ... (add some items to the list)
t first = l[0];

Is there a way to accomplish something similar once dynamic is available?

Was it helpful?

Solution

dynamic doesn't help you much here. You still need to use Type.GetGenericTypeDefinition()/MakeGenericType() to create the object initially, which is less than pleasant.

If I understand it correctly, what dynamic will do is once you have the type constructed that way, it will make it easier to work with. For example, you know you have a list of some type, even if the compiler doesn't. So if you've assigned that list to a dynamic variable you can do things like call it's .Add() method and the call should resolve at run time.

Note that I haven't played with this yet personally, though, so until you try it yourself this is still just hearsay.

OTHER TIPS

You can do that now, though you have to really want it. Observe:

Type t = ...;
typeof(List<>)
    .MakeGenericType(t)
    .GetMethod(...);

Generics and reflection: not really better together, but if you need it...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top