Patrick
Patrick

Reputation: 8300

Abstract property with type declared in derived class?

Is it possible to have an abstract property which returns a type defined in the derived class:

abstract class baseClass
{
    public abstract e_Type type { get; }
}

class derived : baseClass
{
    public enum e_Type
    {
        type1,
        type2
    }

    private e_Type _type;
    public e_Type type { get { return _type; } }
}

or must I return an int and map it in the derived class. Any other suggestions welcome.

Upvotes: 4

Views: 4234

Answers (2)

thecoop
thecoop

Reputation: 46098

Sure you can:

abstract class BaseClass<T>
{
    public abstract T Type { get; }
}

class Derived : BaseClass<EType>
{    
    public enum EType
    {
        type1,
        type2
    }

    private EType _type;
    public override EType Type { get { return _type; } }
}

You don't even need to declare it as abstract:

class BaseClass<T> {
    private T _type;
    public T Type { get { return _type; } }
}

which you can then use as:

BaseClass<EType> classInst = new BaseClass<EType>();

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1499760

Well, you can specify the type explicitly - but it has to be a type, not just "one called e_Type declared within the concrete subclass".

Or you could make it a generic type, of course, like this:

public abstract class BaseClass<T>
{
    public abstract T Type { get; }
}

public class Derived : BaseClass<EType>
{
    public enum EType
    {
        ...
    }

    private EType type;
    public EType Type { get { return type; } }
}

Without knowing what you're trying to achieve, it's hard to suggest an appropriate design.

Upvotes: 5

Related Questions