tags:

views:

71

answers:

2

Is there a way to do this without using the Type class? I would rather to use generics.

abstract class MyAbstract
{
    protected abstract T GetSpecialType();

    private void MyPrivateFunction()
    {
        someT = GetSpecialType();

    }
    private void DoSomething<T>()
    { 
    }
}

class MyConcrete : MyAbstract
{
   protected override T GetSpecialType()
   {
     return SomeReallySpecialClass();
   }
}

I am sure this would work (its the way I have it now), but its ugly.

abstract class MyAbstract
{
    protected abstract Type GetSpecialType();

    private void MyPrivateFunction()
    {
        Type someT = GetSpecialType();

    }
    private void DoSomething(Type ofT)
    { 
    }
}

class MyConcrete : MyAbstract
{
   protected override Type GetSpecialType()
   {
     return typeof(SomeReallySpecialClas();
   }
}

or

Should I put it as a generic parameter on the abstract class?

A: 

I can't quite work out what you are trying to achieve. (If I'm heading in the wrong direction with this answer, you might want to clarify your question a bit and add some details of what it is you are trying to do)


If you are just trying to create new objects based on a generic type parameter, you might want to take a look at the new constraint.

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

By including the "new" constraint it ensures that any type provided when creating the ItemFactory class must have a public parameterless constructor, which means you can create new objects inside the class.

Simon P Stevens
+2  A: 

It's not completely clear to me what you're trying to do, but perhaps something like this?

abstract class MyAbstract<T>
{
    private void DoSomething()
    {
        // Use typeof(T) here as needed
    }
}

class MyConcrete : MyAbstract<SomeReallySpecialClass>
{
    // Is there any other logic here?
}
kvb
I'm thinking this is the best way.
Daniel A. White