views:

70

answers:

3
+2  Q: 

DLR and reflection

Everywhere I read about the new DLR in .net 4, they say that a good use for it is reflection, and the code snippet always shown is something like

dynamic d = GetSomeObject();
d.DoSomething();
d.SomeMember = 1;

What does GetSomeObject() look like? I can't find anywhere that explains that.

I understand that it can be anything, but in the context of reflection what is it? Is it the assembly? an instance of a type?

A: 

Well, GetSomeObject() could, for instance, return an instance of type _ComObject. That's one of the primary reasons of having it dynamic, I think.

Dmitri Nesteruk
+2  A: 

The return type of GetSomeObject() will be an instance of some type. For example, here's what it might look like:

public Customer GetSomeObject() {
    return new Customer("John", "Doe", 12345);
}

And then the code would say:

dynamic customer = GetSomeObject();
string s = customer.FirstName;
// now the "s" variable would have "John" in it

The GetSomeObject() can return anything. It might return a Customer object or a Product. And it doesn't matter! The idea is that when the variable is declared as being dynamic that when you call a method or a property, as you have shown, the compiler will generate code that uses Reflection to try and call the method or property. If they exist then the calls will succeed. If not then you'll get an error at runtime.

In the general case this example is just simplifying the usage of Reflection by having the compiler generate the code for you.

Having said that, if the Customer or Product object implement IDynamicObject themselves then they can do far more advanced stuff.

Eilon
+1  A: 

What you are describing is the duck-typing aspect of dynamic (there are other facets). The answer is that it could be anything:

  • a true dynamic object (IDynamicObject)
  • any regular object, via reflection

A useful example (for reading properties, at least) might be an anonymous type; it could also be a COM object, for example - or (in Silverlight) an object in the html DOM. Or it could be your vendor's Customer object that doesn't implement any common interface, but is remarkably like your own InternalCustomer object. Heck, it could be an IronPyton object.

Marc Gravell
I understand that it can be anything. I updated my question to be a little more specific
Joe