Matias Cicero
Matias Cicero

Reputation: 26281

Extending from a generic parameter

Let's suppose I write this class:

public A<T> : T
{
}

Basically, I want A to extend from (inherit) whatever T is.

For instance, if I have this:

public class B
{
     public string Name { get { return "B"; } }
}

I should be able to accomplish something like this:

B instance = new A<B>();
Console.WriteLine(instance.Name);

which doesn't compile.

How can I extend from a generic argument?

If it can't be done, why is it not possible?

Upvotes: 1

Views: 46

Answers (3)

MikeH
MikeH

Reputation: 4395

Perhaps rather than trying to create a class that inherits generics you could create an extension method to perform the task you're looking for.

public static void ExtensionTest<T>(this T test)
{
  Console.WriteLine("ExtensionTest");
}

In use:

var b = new B();
b.ExtensionTest();

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

you could make it work:

class Program
{
    public static void Main()
    {
        B instance = new A<B>();
        Console.WriteLine(instance.Name);
        Console.Read();
    }
}

public class A<T> : B where T : B { }

public class B
{
    public string Name { get { return "B"; } }
}

Although, A should really just inherit from B directly here. Not sure what your end goal is.

Upvotes: 0

Fenton
Fenton

Reputation: 250822

You can't do this because even though you could write a constraint to say "it has to be a class"...

// NOT WORKING CODE...
public class B<T> : T where T : class

... there is no guarantee the class isn't sealed.

This is why the compiler says you can't do it.

What you can do is create a real base class and constrain T to that base class and inherit from the base class...

public class B<T> : BaseType where T : BaseType

Example:

public class BaseClass
{
}

public class A : BaseClass
{
}

public class B<T> : BaseClass where T : class
{
}

Usage:

var x = new B<A>();

Upvotes: 1

Related Questions