Question

C# 4.0 introduces dynamic keyword, which will look up at run-time.

Does this mean we'll need awkward reflection no more? If does, Can you show up an example of it?

Was it helpful?

Solution

We'll still have Reflection - using 'dynamic' against regular CLR objects will invoke a Reflection-based dispatcher.

So - we'll still have Reflection, but it'll be easier to do.

Here's an example:

// Via 'dynamic'    
dynamic dx = GetSomeCLRObject();
dx.DoSomething();
dx.SomeMember = 2;

// Via Reflection
object x = GetSomeCLRObject();
Type xt = x.GetType();
MemberInfo DoSomethingMethod = xt.GetMethod("DoSomething");
DoSomethingMethod.Invoke(x, null);
PropertyInfo SomeMemberProperty = xt.GetProperty("SomeMember");
SomeMemberProperty.SetValue(x, 2);

I don't know about you, but I like the former. =)

In both these cases, I get no compile-time checking, no Intellisense, no IDE support - but the former case is much more expressive than the latter.

OTHER TIPS

Dynamic dispatch is only one possible use of Reflection. There are many good reasons to interrogate a class for its structure, get information about that structure and visualize in some form or act on it in some way without ever dynamically accessing members. Reflection is here to stay. :)

If you want examples of the dynamic keyword, here is a video from PDC of the man himself talking about it (and other stuff C# 4.0 related).

Dynamic will go a long way to solving problems with methods known only by name, where that name is known and fixed at compile time - but of course, such methods could also be expressed as interfaces if you control the types.

There are cases where dynamic would not help at all:

  • where the method name isn't known at compile time (i.e. it is loaded from config / user input)
  • object creation
  • maybe some generics scenarios

The biggest uses I see for dynamic are:

  • COM interop (obviously)
  • generic operator support
  • duck typing where there is no common interface
  • DLR interop (see comments)

But it definitely doesn't solve every reflection woe.

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