Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Call shadow method with generic cast

I'm trying to write a method which casts an object to a generic type to execute a specific shadow method. This is my test code:

class Program
{
    static void Main(string[] args)
    {
        hello2 h2 = new hello2();
        test(h2);
        Console.ReadLine();
    }

    static void test(hello h)
    {
        h.write2<hello2>();
    }
}

class hello
{
    public virtual void write()
    {
        Console.WriteLine("hello");
    }

    public void write2<T>() where T : hello
    {
        T h2 = (T)this;
        hello2 h21 = (hello2)this;
        h2.write();
        h21.write();
    }
}

class hello2 : hello
{
    public new void write()
    {
        Console.WriteLine("hello2");
    }
}

My Console Output is:

hello

hello2

I debugged it, checked everything and couldn't find a mistake. The Output should be hello2 in both cases. Am I missing something obvious here? Or is this just not working?

like image 449
Sebastian L Avatar asked Oct 28 '25 06:10

Sebastian L


1 Answers

The thing you are missing is the method that is called is chosen at the compile time of hello not at the use of write2. So at compile time all the compiler knows is that T is of type hello or some other derived class so it chooses the shadowed method as that is the only method it knows about at compile time.

Think of it this way, replace every T with whatever is on the right side of the :. This is what the compiler sees and uses that information to make its choices.

//What the complier sees when you compile even if you pass in hello2 as T.
public void write2<T>() where T : hello
{
    hello h2 = (hello)this;
    hello2 h21 = (hello2)this;
    h2.write();
    h21.write();
}
like image 172
Scott Chamberlain Avatar answered Oct 29 '25 22:10

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!