Question

I'm trying to make a generic virtual method, but for some reason the override is ignored. An identical non-generic implementation works as expected

Here's the essentials of the code in question:

EDIT: Turns out this might be more obscure than I anticipated - I'm using Unity/Mono, and it's not working there, but it is working in VS

EDIT: Adding things to make it a complete program

public interface IController
{
    void Set<T>() where T : class, IController;
    void Set(Type t);
}

public abstract class Controller : IController
{
    public IController parent;
    public virtual void Set<T>() where T : class, IController
    {
        Console.WriteLine(GetType());
        parent.Set<T>();
    }
    public virtual void Set(Type t)
    {
        Console.WriteLine(GetType());
        parent.Set(t);
    }
}

public class ControllerGroup : Controller
{
    public override void Set<T>()
    {
        Console.WriteLine("Success!");
    }
    public override void Set(Type t)
    {
        Console.WriteLine("Success!");
    }
}

static class Program
{
    static void Main()
    {
        IController obj = new ControllerGroup();
        obj.Set<Controller>();
    }
}

EDIT/Clarification: The output should be "Success!" but instead it is "ControllerGroup", then of course a null reference exception

I'm accessing this method through an IController interface, which declares both these methods. Unsure if that affects anything

Anyway, the problem is that the override for the generic method is just ignored. The console output shows that the object type is indeed ControllerGroup, but this seems to have no effect.

Was it helpful?

Solution

Found the problem. It seems that in Unity/Mono, if an interface has a generic method, the 'callvirt' opcode doesn't properly traverse the hierarchy and just takes the first method it finds. So doing this fixed the problem:

void IController.Set<T>()
{
    Set<T>();
}

Since, within the method, this is a class and not an interface, the bug is worked-around.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top