tags:

views:

380

answers:

2

What are the performance implications of attaching methods and properties at run time using dynamic features, as described in this blog post?

What are the practical uses of ExpandoObject?

+6  A: 

Well, you're not really attaching methods and properties to the object. Not as far as the CLR is concerned. You're just adding entries into a dictionary, and when the ExpandoObject implementation of IDynamicMetaObjectProvider is asked for the property value (or asked to execute the method) it will act accordingly.

Performance is obviously going to be slower than statically bound access to methods/properties, but the DLR is pretty nippy. My personal worry isn't performance so much as the lack of type safety - a typo can easily screw your code up without the compiler spotting it.

My personal advice is to only use dynamic typing in C# 4 where it gives a very clear benefit... which I expect to be relatively rare (like unsafe code).

Uses for ExpandoObject? Not that many, IMO - mostly when talking to other dynamic languages.

Jon Skeet
Whoa, this begins to look like prototype-based programming. Besides that, could it be used to emulate [per-assembly] base class injection?
Cecil Has a Name
Relatively rare?! You sir, are not a Ruby programmer :)
Paul Betts
@Paul: Indeed... because we're talking about C#, rather than Ruby. As a basically statically typed language, I believe it will be relatively rare to turn C# into a mish-mash of static and dynamic typing. If you want to use dynamic typing extensively, use IronRuby or IronPython...
Jon Skeet
Thanks Jon. I should then rephrase what ruby can achieve using dynamic features that c# can't
Web2
@Web2: I suggest you ask that in a different post... and it's a topic I'm supremely unqualified to talk about, being a statically typed guy at heart :)
Jon Skeet
+1  A: 

ExpandoObject relates to the DLR, and is primarily related for playing between C# and a dynamic language (perhaps IronPython); however, more generally this type of property-bag object can be useful when the schema of your types is only known at runtime, perhaps based on database data / configuration data. Perhaps an example of the "inner platform" anti-pattern, but it is useful in specific scenarios to attach properties at runtime. Of course, for purely CLR usage (i.e. no DLR callers) you can do this a lot more simply just with an indexer and dictionary:

obj["Name"] = "Fred";
string name = (string) obj["Name"];

For data-binding purposes, even with this you can achieve full data binding using custom property descriptors, via ICustomTypeDescriptor or TypeDescriptionProvider.

Or for a simple example: consider DataTable... this is in part what you can do here (again, in static-typed code): (untested example)

DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
DataRow row = table.Rows.Add("Fred");
Marc Gravell