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.
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.
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.
Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.
A private virtual function can be overridden by derived classes, but can only be called from within the base class.
You can use delegates or Func
s 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."
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With