Question

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?

Was it helpful?

Solution

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 :)

OTHER TIPS

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.

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.

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);

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.

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