jp2code jp2code - 19 days ago 5
C# Question

Override Method Group On-The-Fly

I have a base class that implements an interface:

internal interface ITest
{
virtual void GetData();
}

internal class Test : ITest
{
public void GetData()
{
Console.WriteLine("Test - Hello World!");
}
}


It is used by inheriting the Test class and overriding the GetData() method:

internal class SubTest : Test
{
public override void GetData()
{
Console.WriteLine("SubTest - Hello World!");
}
}


I have hundreds of stored procedures that each need to be called 1 time. Creating a new class like SubTest for each stored procedure that inherits from Test seems like overkill.

Is there a way to write a Lambda Expression, Anonymous Method, or Action that will let me override the empty default method?

What I'm thinking is something along these lines:

var t = new Test();
t.GetData = delegate()
{
Console.WriteLine("Anonymous - Hello World!");
};


Is there any way to write an override for a method on-the-fly like that?

Solved!



I used Evk's technique to apply what Gusman showed:

internal interface ITest
{
virtual void GetData();
}

internal class Test : ITest
{
public void GetData()
{
Console.WriteLine("Call from Test");
}
}

internal class SubTest : Test
{
private readonly Action _localTest;
public SubTest(Action localTest)
{
_localTest = localTest;
}
public override void GetData()
{
base.GetData();
_localTest();
}
}


Here is how I implemented it:

class ClassTester
{
public void Run()
{
var t = new Test(() =>
{
Console.WriteLine("Anonymous Override of Test");
}
);
t.GetData();
}
}

Evk Evk
Answer

If I understand you correctly you can just do

class DynamicTest : Test {
    private readonly Action _getData;
    public DynamicTest(Action getData) {
        _getData = getData;
    }
    public override void GetData() {
        _getData();
    }
}

And then

var test = new DynamicTest(() => {
      Console.WriteLine("Dynamic");
});