Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force call a C# derived method

I have a class that is generated by some tool, therefore I can't change it. The generated class is very simple (no interface, no virtual methods):

class GeneratedFoo
{
  public void Write(string p) { /* do something */ }
}

In the C# project, we want to provide a way so that we can plug in a different implementation of MyFoo. So I'm thinking to make MyFoo derived from GeneratedFoo

class MyFoo : GeneratedFoo
{
  public new void Write(string p) { /* do different things */ }
}

Then I have a CreateFoo method that will either return an instance of GeneratedFoo or MyFoo class. However it always calls the method in GeneratedFoo.

GeneratedFoo foo = CreateFoo(); // if this returns MyFoo,
foo.Write("1"); // it stills calls GeneratedFoo.Write

This is expceted since it is not a virtual method. But I'm wondering if there is a way (a hack maybe) to make it call the derived method.

Thanks,
Ian

like image 535
Hengyi Avatar asked Aug 13 '09 23:08

Hengyi


2 Answers

Adam gave you an answer (correct one). Now it's time for hack you were asking for :)


class BaseFoo
{
    public void Write() { Console.WriteLine("Hello simple world"); }
}

class DerFoo : BaseFoo
{
    public void Write() { Console.WriteLine("Hello complicated world"); }
}

public static void Main()
{
    BaseFoo bs = new DerFoo();
    bs.Write();

    bs.GetType().GetMethod("Write").Invoke(bs, null);
}

Prints out:

Hello simple world
Hello complicated world
like image 174
Marcin Deptuła Avatar answered Oct 21 '22 09:10

Marcin Deptuła


Without being able to make the method virtual, no. A non-virtual method is statically linked at compile time and can't be changed.

like image 23
Adam Robinson Avatar answered Oct 21 '22 10:10

Adam Robinson