What you can do is create a class extension. It is not possible to add new methods at runtime, but you can do something like this:
public class OneClass { private List<object> items; public List<object> Items { get { return items; } } public void AddOne(object item) { items.Add(item); } }
if you want to extend the behavior of this class, you can write an extension class. Like this:
public static class OneClassExtensions { public void AddMany(this OneClass self, params object[] items) { foreach(object item in items) { self.Items.Add(item); } } }
In this way, you can call this extension method from OneClass objects:
OneClass obj = new OneClass(); obj.AddOne("hello"); obj.AddMany("Hello", "world");
The following rules apply:
- The extension class must have the `static 'modifier
- you need to prefix `this' with the first argument. This argument will be the object itself.
- To use this extension class in your code, you must use the namespace that this extension class contains, for example, `use Some.Namespace.That.Has.An.Extension 'in each .cs file in which you want to use extension methods.
source share