Im trying to add function on runtime , something like that :
static void Main()
{
dynamic d = new Duck();
d.Quack =(Action) (() => Console.WriteLine("1")); //decalre a new method on runtime ??
d.Quack();
}
public class Duck : System.Dynamic.DynamicObject
{
//...
}
‘UserQuery.Duck’ does not contain a definition for ‘Quack’
Isnt dynamic should allow me to do it ?
does brand new ExpandoObject is the only solution ?
i have my Duck class already. how can i make it Expando ? – can i make duck act like expando ?
You can’t add properties of any type (even functions) to an existing type.
You could use ExpandoObject though:
Don’t be confused with what the dynamic type does.
Now I can do :
speak(new Duck());andspeak(new Goose());, it will compile and run if bothDuckandGoosehave the methodQuack(), if they don’t, it raises an exception. (The same one you get)When you call a method/property on a
dynamictype, it only resolves that at runtime and doesn’t do a compiler check.The ExpandoObject allows you to create properties on the fly.
To answer your question on the comment, the way I see it is, if you need your own class which needed the ability to create new properties you could inherit from DynamicObject. Like this (adapted from this msdn page):
Then you could do: