Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "class A : B<C>" and "class A<T> : B<T> where T : C"?

Tags:

c#

generics

I am trying to create a derived class from a generic class, and I was wondering what the differences are between

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

and

public class A: B<C>
{
}

Inside class A there probably will be no code, since (for now) it will not behave different from class B. I only want to distinguish the two classes.

Thanks in advance.

like image 835
ffonz Avatar asked Oct 04 '13 14:10

ffonz


3 Answers

Say you had a class

public class D : C
{
}

Then in your first example the below is valid.

var a = new A<D>

You can use any class for T that is ultimately derived from C.

Whereas your second code is hard coded to have B use C for the genric type parameter and is not generic.

like image 116
Ben Robinson Avatar answered Nov 10 '22 20:11

Ben Robinson


It is a Constraints with generics in C#, for sample:

In

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

The generic T must be a C type or a child of it (what is a abstraction).

In

public class A: B<C>
{
}

The generic is C.

like image 28
Felipe Oriani Avatar answered Nov 10 '22 20:11

Felipe Oriani


In your first example, A is a generic class, of type C. It also inherits from class B of type C.

Your second example has the following properties:

A is not a generic class. It inherits from class B of type C.

So, they are actually quite different.

like image 2
Simon Whitehead Avatar answered Nov 10 '22 20:11

Simon Whitehead