Search code examples
c#genericsinheritanceabstract-class

c# call generic method from abstract class passing inheriting type


I'm going to explain better what I mean.

I think what I desire is not possibile, however I'll try.

I have a static class who have this method:

public static class BaseTypeID
{
    static ulong _id = 1;

    public static ulong NextID => _id++;
}

public static class TypeID<T> where T : class
{
    public static readonly ulong ID = 0;

    static TypeID()
    {
        ID = BaseTypeID.NextID;
    }
}

public static class Register
{
    public static void PrintType<T>(T passedVar) where T : AbstractType
    {
         Console.WriteLine(TypeID<T>.ID);
    }
}

I have the abstract class who call this method:

public abstract class AbstractType
{
    public void UseStaticMethod() => Register.PrintType(this);
}

And Inheriting class:

public class InheritingType : AbstractClass { }

Actually, if I do:

InheritingType myVar = new InheritingType();
myVar.UseStaticMethod();

it prints ID of AbstractClass instead InheritingType ID. Is there a way to call the InheritingType's ID without writing an override method?

Thank you so much


Solution

  • It is technically possible if you dynamically dispatch PrintType,

    public void UseStaticMethod() => Register.PrintType((dynamic)this);
    

    But if you are only using TypeID<T> in this dynamic way, you should consider changing TypeID to be a non-generic and non-static class. Have it work with Type objects instead of generic type parameters.