Enzojz
Enzojz

Reputation: 969

How do I declare the constructor for a generic class with a generic base class with parameters?

I want to do something like this:

abstract class Exception : ApplicationException
{
    protected Exception(string _message) : base(_message)
    {            
    }

    public Exception()
        : base()
    {
    }
}



class TException<P> : P
    where P : Exception
{
    static string messageStd;

    public TException()
        : base(messageStd)
    {
    }
}

Where I suppose any class under TException should be a children be Exception and TException

Just like this:

C is TException<B>, where
B is TException<A>, where
A is TException<Exception>

So we have:

C is C:B
B is B:A
A is A:Exception

but C# told me the base() in the constructor is of type object, not what I supposed to be P:Exception

Is anyone know if it's possible to make this?

Upvotes: 1

Views: 93

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109547

This is fundamentally impossible.

The problem is that you are not allowed to derive a generic class from a type parameter, which you are trying to do with

class TException<P> : P

If you actually try to compile your code, you'll see this error:

Cannot derive from 'P' because it is a type parameter

The other error you are seeing (about the Object() base) is an artifact.

Note that the reason you can't derive a generic class from a type parameter is that this must be guaranteed to work at compile time, but there is no language support for constraining the type so that it is a non-sealed class.

Upvotes: 2

Related Questions