Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding virtual methods when instantiating a class

Tags:

c#

I have a class with some virtual functions, let's pretend this is one of them:

public class AClassWhatever
{
    protected virtual string DoAThingToAString(string inputString)
    {
        return inputString + "blah";
    } 
}

I want to instantiate this class while overriding "DoAThingToAString" inline, much like I can declare properties inline in a declaration, as follows:

...

AClassWhatever instance = new AClassWhatever
{
    DoAThingToAString = new function(string inputString)
    {
        return inputString + inputString + " fill my eyes."
    }
}

...

And now for "instance", DoAThingToAString is overridden with that definition. I need to be able to define the default behavior in the class definition and only override it as needed, differently different times, and I don't want to proliferate a bunch of subclasses to do this.

I know I need to use delegates or something similar, but I've been out of the syntax game for way too long and google was giving me too much irrelevant info.

like image 753
kamii Avatar asked May 24 '13 18:05

kamii


People also ask

Can you override a virtual method?

A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.

Is it mandatory to override virtual method?

It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.

Do you have to override virtual methods C#?

Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.

Can you override private virtual methods?

A private virtual function can be overridden by derived classes, but can only be called from within the base class.


1 Answers

You can use delegates or Funcs to do this.

First, add this to your AClassWhatever class:

public Func<string, string> DoAThingToAString = (x) => x + "blah";

Now you can use the same syntax to override the action.

AClassWhatever instance = new AClassWhatever()
{
    DoAThingToAString = (x) => x + x + " fill my eyes."
};
like image 51
gunr2171 Avatar answered Sep 22 '22 12:09

gunr2171