Search code examples
c#classderived

Reference inherited class's <T>ype in a derived class


I don't know if its possible or not, but here's what I need. I'm toying around with something and want to know if its possible since you can't create your own data type based on a sealed type such as int, Int32, Int64, etc.

I want to create a top-level class that is defined of a given type with some common stuff. Then, derive this into two subclasses, but in this case, each class is based on either and int or Int64 type. From THAT instance, create an instance of either one and know its yped basis for parameter referenc / return settings.

So when I need to create an instance of the "ThisClass", I don't have to know its type basis of either int or Int64, yet IT will know the type and be able to allow methods/functions to be called with the typed... This way, If I want to change my ThisClass definition from SubLevel1 to SubLevel2, I don't have to dance around all different data type definitions.

Hope this makes sense..

public class TopLevel<T>
{
    ... 
}

public class SubLevel1 : TopLevel<int>
{
    ...
}

public class SubLevel2 : TopLevel<Int64>
{ 
    ...
}

public class ThisClass : SubLevel1
{
    ...
    public <based on the Int data type from SubLevel1> SomeFunc()
    {  
        return <the Int value computed>;
    }
}

Solution

  • I assume SomeFunc should be present in all subclasses of TopLevel<T> so you should define it there:

    public abstract class TopLevel<T>
    {
        public TopLevel()
        {
        }
    
        public abstract T SomeFunc();
    }
    

    and specific subclasses will know the generic type parameter, so ThisClass would define SomeFunc as:

    public class ThisClass : SubLevel1
    { ...
       public override int SomeFunc()
       {  
          return <the Int value computed>;
       }
    }