Reputation:
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?
Upvotes: 3
Views: 456
Reputation: 604
I think that it's more interesting, as far as dynamic, DLR and reflection concerns, to see what happend in line 2 for instance.
using dynmic you go like this dynamic d = GetSomeObject(); d.DoSomething();
while with reflection it's a bit more noisy
var d = GetSomeObject();
var mi = d.GetType().GetMethod("DoSomething");
mi.Invoke(d,mi);
As I see it, the first one is more elegant and we are talking about an argument less method, things can go really crazy when you are interoping with COM or APIs with long signature methods. I been there ;)
Upvotes: 0
Reputation: 25704
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.
Upvotes: 3
Reputation: 1064224
What you are describing is the duck-typing aspect of dynamic
(there are other facets). The answer is that it could be anything:
IDynamicObject
)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.
Upvotes: 1
Reputation: 23798
Well, GetSomeObject()
could, for instance, return an instance of type _ComObject
. That's one of the primary reasons of having it dynamic
, I think.
Upvotes: 0