views:

820

answers:

8

What is their use if when you call the method, it might not exist?

Does that mean that you would be able to dynamically create a method on a dynamic object?

What are the practical use of this?

+7  A: 

You won't really be able to dynamically create the method - but you can get an implementation of IDynamicMetaObject (often by extending DynamicObject) to respond as if the method existed.

Uses:

  • Programming against COM objects with a weak API (e.g. office)
  • Calling into dynamic languages such as Ruby/Python
  • Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g. document.RootElement.Person[5].Name["Attribute"]
  • No doubt many more we have yet to think of :)
Jon Skeet
I really like that XML idea. Would this involve some sort of custom property bag?
tsilb
It would be a bit like a property bag, but I'd expect it to wrap the LINQ to XML objects and look elements up when needed rather than fetch them all on creation. The names have changed a bit since I wrote this - I'll update...
Jon Skeet
+1  A: 

First of all, you can't use it now. It's part of C#4, which will be released sometime in the future.

Basically, it's for an object, whose properties won't be known until runtime. Perhaps it comes from a COM object. Perhaps it's a "define on the fly object" as you describe (although I don't think there's a facility to create those yet or planned).

It's rather like a System.Object, except that you are allowed to call methods that the compiler doesn't know about, and that the runtime figures out how to call.

James Curran
Actually, there is such a facility, ExpandoObject.
Kaerber
A: 

The two biggies I can think of are duck typing and the ability to use C# as a scripting language in applications, similar to javascript and Python. That last one makes me tear up a little.

Will
+1  A: 

See this question with good answers

Hugo
A: 

Some good examples of using dynamic can be seen at http://channel9.msdn.com/pdc2008/PC16/

It does mean that possibly that office could be converted to managed code and still keep the com interface for all the old macros :)

MrJavaGuy
+1  A: 

Sorry the above link does not seem to be working correctly, start at http://microsoftpdc.com/ and you can navigate through the session to get to the video.

MrJavaGuy
A: 

I see several dynamic ORM frameworks being written. Or heck write one yourself.

I agree with Jon Skeet, you might see some interesting ways of exploring objects. Maybe with selectors like jQuery.

Calling COM and calling Dynamic Languages.

I'm looking forward to seeing if there is a way to do a Ruby-like missing_method.

tyndall
A: 

Think of it as a simplified form of Reflection. Instead of this:

object value = GetSomeObject();
Method method = value.GetType().GetMethod("DoSomething");
method.Invoke(value, new object[] { 1, 2, 3 });

You get this:

IDynamicObject value = GetSomeObject();
value.DoSomething(1, 2, 3);
Adam Ruth