tags:

views:

68

answers:

3

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>
{
 ... 
}

pubic 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>;
   }
}
+1  A: 

That can't be done at compile time without paramterizing all of the derived classes :

public class ThisClass<T> : SubLevel1<T> etc etc

You could do it at runtime with reflection by inspecting typeof(ThisClass).BaseType etc. but that could get pretty messy as you need to write code that understands the inheritance and generic type parameter hierarchy of the entire base class trunk.

dkackman
+2  A: 

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>;
   }
}
Lee
that was the expectation, but didn't necessarily want to fill out some of these to the abstract level, but working... thanks
DRapp
A: 

You cannot do this as asked.

However, you can write using MyType = System.Int32; at the top of the file, then use MyType everywhere in the file. This will allow you to change types easily.

SLaks