Zacryon
Zacryon

Reputation: 689

Is it possible to change the type used in a method of a base class from within a derived class without modifying the base class?

Suppose we have four classes A, B, T and U, which look something like this:

using System;
using bla;


public class T
{
    public void method()
    {
        Console.WriteLine("I am using T.");
    }
}

public class U : T
{
    public new void method()
    {
        Console.WriteLine("I am using U.");
        // other stuff...
    }
}

public class A
{
    public T t;
    public void method()
    {
        t = new T();
        t.method();
        // some important manipulations of t...
    }
}

namespace bla{
    using T = U;
    public class B : A
    {
        public new void method()
        {
            // now use type U instead of T in the base method.
            base.method();
            // other stuff...
        }    
    }
}

public class Test
{
    public static void Main()
    {
        B b = new B();
        b.method();
    }
}

I want to achieve that when the base method base.method() is called from within class B actually type U is used and not type T. Such that the output of the Main() method would be:

I am using U.

Is it possible to achieve this in C# without having to modify class A and/or T? Something like a using directive would be nice. The above code - obviously - doesn't work as I want. I also thought about using reflection, but I am not sure if it is possible to use reflection in this case without having to instantiate a new (anonymous) object or reference an existing one (both would not be nice in my case).

Otherwise I would have to modify class A (resp. class B as an almost 100% line-by-line copy) by either substituting each T with U or by inserting a using directive at the beginning (or accepting parameters, or using templates, or whatever). Either way I would find this not very neat and I wonder if it is achievable somehow better.

Am I missing something obvious? Thanks in advance for any help!

Upvotes: 0

Views: 381

Answers (2)

J.B. Schubert
J.B. Schubert

Reputation: 31

I didn't try it out yet, but you I'm sure casting the object into the base-class you want could help.

Like this:

((U)this).method();

EDIT: The reason type T is used, instead of type U, is that there there is an instance of type T in class A.

Upvotes: 0

Aly Elhaddad
Aly Elhaddad

Reputation: 1953

Short answer: no, given the current structure, it's not possible to make base.method() that's called from B to use method of U instead of T without modifying neither A nor T. However, why won't you just:

public class B : A
{
    public new void method()
    {
        U u = new U();
        u.method();
    }    
}

Upvotes: 1

Related Questions