Reputation: 3137
So basically I have an object that takes instances and adds them to a list. Each instance uses virtual methods, which I need to override once the instance is created. How would I go about overriding methods of an instance?
Upvotes: 6
Views: 12498
Reputation: 16922
That's not possible at runtime. You cannot change a class' behaviour once it has been instantiated. You could however look into creating a delegate method.
EDIT, just saw the first answer, go with that ;)
Upvotes: 0
Reputation: 7591
C# is static once the object is created you cannot change the behavior of the object. you can subclass a superclass using inhertance, but this is done at designtime, not runtime.
class foo
{
public virtual void dosomething()
{
console.writeline("this is foo");
}
}
class bar : foo
{
public override void dosomething()
{
console.writeline("this is bar");
}
}
var list = new Foo[]{new foo(), new bar()};
There is also the concept of AOP - aspect oriented programming. This is where you can begin to inject behavior at runtime. there are 2 frameworks that I'm aware of that do this
Upvotes: 0
Reputation: 245389
You can't. You can only override a method when defining a class.
The best option is instead to use an appropriate Func
delegate as a placeholder and allow the caller to supply the implementation that way:
public class SomeClass
{
public Func<string> Method { get; set; }
public void PrintSomething()
{
if(Method != null) Console.WriteLine(Method());
}
}
// Elsewhere in your application
var instance = new SomeClass();
instance.Method = () => "Hello World!";
instance.PrintSomething(); // Prints "Hello World!"
Upvotes: 16