Reputation: 2245
I want to mock the implementation of Parent
class Test2 method so that it should return the child implementation.
public class Program
{
static void Main(string[] args)
{
var child = new Child();
child.print();
Console.ReadLine();
}
}
//Parent Class
public class Parent
{
public void print()
{
Test1();
}
protected void Test1()
{
Test2();
}
protected void Test2()
{
Console.WriteLine("Parent Test2");
}
}
//Child Class
public class Child : Parent
{
protected void Test2()
{
Console.WriteLine("Child Test2");
}
}
Output : Parent Test2
But I want output to be Child Test2. Is there any way I can do this without modifying any code in parent class.
Upvotes: 0
Views: 136
Reputation: 3284
If you really want to do it without having virtual
in the Parent
, you can define the following in Child
:
public new void print()
{
Test2();
}
Then, change the definition of Test2()
to also include the new
keyword. However, I wouldn't recommend this over just declaring Test2()
as virtual
if you can help it.
Simply defining both methods will already hide the implementation in the base class, but adding the new
keyword makes it explicit that it is what you're intending to do. Without the keyword, you will get a compiler warning as well.
Upvotes: 0
Reputation: 1076
You can do that but it is rather suggested to be left only for testing and research purposes as it would be a huge hack.
Have a look at this article: http://www.codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer
In short words what you would have to do is to get the method handle at runtime and replace it for another method that implementes the call in the way you like. Then you can use reflection to access any other method.
This will work but should be avoided for any commercial and productive solutions I think.
Upvotes: 0
Reputation: 203821
Test2
needs to be marked as virtual
in Parent
and override
in Child
to have the semantics you want.
There is no way to have the semantics you want without modifying the Parent
class.
Upvotes: 1