Search code examples
c#classoverridingvirtualinheritance

C# Override virtual function without having to implement another class


I am trying to override a virtual function only for a single defined element (without having to create another class that implements it and then adding a function to override it..).

Example:

public class MyClass
{
    public virtual bool ChangeStatus(String status)
    {
        return false;
    }
}


void test()
{
    //The following is written as an example of what I am trying to achieve & does not work
    MyClass blah = new MyClass()
    {
        public override bool ChangeStatus(String status)
        {
            return true;
        }
    };
}

Any idea how to achieve this?

Thanks.


Solution

  • if you have control over MyClass, you can let the desired method call a delegate which can be replaced for every single object at runtime...

    class MyClass
    {
        public void Func<SomeParameterType,SomeReturnType> myDelegate {get;set;}
        public SomeReturnType myFunction(SomeParameterType parameter)
        {
            if(myDelegate==null)
                throw new Exception();
            return myDelegate(parameter);
        }
    }
    
    ...
    
    MyClass obj = new MyClass();
    SomeParameterType p = new SomeParameterType();
    obj.myDelegate = (x)=>new SomeReturnType(x);
    SomeReturnType result = obj.myFunction(p);