peelz
peelz

Reputation: 2940

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.

Upvotes: 1

Views: 3884

Answers (4)

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

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);

Upvotes: 1

bash.d
bash.d

Reputation: 13207

C# is strictly built on the concept of classes. You cannot create a function/method without a class.
Additionally, virtual/override implies inheritance, so you MUST derive from this class.

Upvotes: 0

Parimal Raj
Parimal Raj

Reputation: 20565

You cannot override a function without inheriting the class, the whole point of a virtual function is that it can be overridden in the child class.

If your are doing it withing the same class, wouldn't you end up writing a simple method/function for the class ?

So, follow the OOP programming concept, it is designed for simplicity & ease of programming. Instead simply inherit the class and override the function

Upvotes: 0

Related Questions