views:

185

answers:

1

Does C# 4.0's ExpandoObject support Prototype-based inheritance? If not, why not(was it by design?) and how could this be implemented? If yes, how does it work and differences are there to the way it works in Javascript?

+6  A: 

Does C# 4.0's ExpandoObject support Prototype-based inheritance?

First off, note that the ExpandoObject class has nothing whatsoever to do with C# 4.0. The C# team did not design or implement this object. C# 4.0 and the ExpandoObject class merely happen to both ship with the latest version of .NET.

To answer your question I refer you to the documentation for ExpandoObject, which clearly states:

The ExpandoObject class is an implementation of the dynamic object concept that enables getting, setting, and invoking members. If you want to define types that have their own dynamic dispatch semantics, use the DynamicObject class.

As the documentation states, if you want custom dispatch semantics above mere invoking of members then use the DynamicObject class.

If not, why not? was it by design?

Someone might want an expando object but that person might neither want nor need prototype inheritance. Expando objects do not logically require any form of inheritance.

how could this be implemented?

Use the DynamicObject object. Write your own prototype inheritance mechanism.

If yes, how does it work and differences are there to the way it works in Javascript?

If you are attempting to write your own prototype inheritance that is exactly like JScript's, I encourage you to read the ECMAScript specification extremely carefully. Prototype inheritance looks simple, but there are subtleties that most people get wrong. For example, even JScript experts often get this little puzzle wrong. What does this JScript code print?

var Animal = new Object(); 
function Reptile() { } 
Reptile.prototype = Animal; 
var lizard = new Reptile(); 
print(lizard instanceof Reptile); // this is true
print(lizard.constructor == Reptile);  // is this true or false? explain your answer!

Prototype inheritance does not always work the way you think it does! For an explanation of what this prints and why, see my article on the subject.

Eric Lippert