Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching properties and methods at runtime in C# 4.0?

Tags:

c#

.net

dynamic

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?

like image 810
Web2 Avatar asked Sep 08 '09 13:09

Web2


2 Answers

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.

like image 70
Jon Skeet Avatar answered Nov 05 '22 23:11

Jon Skeet


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");
like image 25
Marc Gravell Avatar answered Nov 06 '22 01:11

Marc Gravell