In regular C # /. NET, the answer is simply no. The most you can do is write DynamicMethod , which can behave like a method of this type (access to private fields, etc.), but it will never be in the API - you just end up with a delegate.
If you use dynamic , you can do almost anything you want. You can emulate this with ExpandoObject by adding delegates instead of methods, but you can do anything with a custom dynamic type, but that only affects those who use the dynamic API. For a basic ExpandoObject example:
dynamic obj = new ExpandoObject(); Func<int, int> func = x => 2*x; obj.Foo = func; int i = obj.Foo(123);
For properties and events (rather than methods), you can use the System.ComponentModel approach to change what appears at run time, but this only affects callers who access through System.ComponentModel , which basically means: bind user data interface. This is how a DataTable presents columns as pseudo-properties (forgetting about the “typed data sets” at the moment - it works without them).
For completeness, I should also mention extension methods. This is more of a compiler trick rather than a run-time trick, but curious allows you to add methods to an existing type - for small values, add.
One final trick commonly used by ORM, etc., is to dynamically subclass a type and provide additional functions in a subclass. For example, redefining properties to intercept them (lazy loading, etc.).
Marc gravell
source share