Maxime Rouiller
Maxime Rouiller

Reputation: 13699

What is the practical use of "dynamic" variable in C# 4.0?

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?

Upvotes: 14

Views: 5613

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1499770

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

Upvotes: 16

Adam Ruth
Adam Ruth

Reputation: 3655

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

Upvotes: 1

BuddyJoe
BuddyJoe

Reputation: 71101

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.

Upvotes: 0

user1228
user1228

Reputation:

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.

Upvotes: 1

James Curran
James Curran

Reputation: 103485

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.

Upvotes: 3

Related Questions