Michael Edwards
Michael Edwards

Reputation: 6528

Force usages of method using new keyword c#

The following code:

class Program
{
    static P1 p = new P1();
    static void Main(string[] args)
    {
        var t = new P2();
        p = t;
        p.DoWork();
        t.DoWork();
        Console.ReadLine();
    }
}

public class P1
{
    public void DoWork()
    {
        Console.WriteLine("Test1");
    }
}
public class P2: P1
{
    new public void DoWork()
    {
        Console.WriteLine("Test2");
    }
}

Will print out:

Test1
Test2

Is there anyway to force the call p.DoWork() to use the implementation in the P2 class. In reality the class P1 is in a third party compiled assembly so I can't modify any of the code for the P1 class. Normally I would just add the virtual keyword to P1 but this isn't possible.

Upvotes: 2

Views: 174

Answers (3)

urbaindepuce
urbaindepuce

Reputation: 523

You can either cast the P1 instance to P2 like this:

((p2)p).DoWork();

Or you could build a wrapper class which internally uses an instance of P1. All the stuff you need from the internal class gets redirected and you are free to add whatever suits you to the wrapper class.

public class P1
{
    public string SomeProperty { get; set; }

    public int SomeMethod()
    {
        return 0;
    }

    public void DoWork()
    {
        // Do something
    }
}

public class Wrapper
{
    private P1 Instance { get; set; }

    public string ExposedProperty
    {
        get
        {
            return this.Instance.SomeProperty;
        }
    }

    public Wrapper(P1 instance)
    {
        this.Instance = instance;
    }

    public int ExposedMethod()
    {
        return this.Instance.SomeMethod();
    }

    public void DoWork()
    {
        // Do something else
    }
}

This solution would be similar to the facade pattern http://en.wikipedia.org/wiki/Facade_pattern

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

No.

The authors of P1 didn't choose to make their DoWork method virtual. So you can't change what that method does.

Don't introduce a new method with the same name and signature as DoWork from P1. It will lead to confusion. And it won't change the original DoWork in any way. Instead, choose a new name for your own method.

If the functionality of P1 is not in all cases what you need, maybe you shouldn't inherit from P1 at all. Instead your class could hold a private field of type P1 and then some methods of yours could use the "good" functionality of P1.

Upvotes: 3

burning_LEGION
burning_LEGION

Reputation: 13450

the only way, but it is a bad way

class Program
{
    static P1 p = new P1();
    static void Main(string[] args)
    {
        var t = new P2();
        p = t;
        ((P2)p).DoWork();
        t.DoWork();
        Console.ReadLine();
    }
}

Upvotes: 0

Related Questions