Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the preferred syntax for a Generic Class Derivation Constraint?

Tags:

c#

.net

generics

The documented derivation constraint uses a where T : clause and the sample code that I'm tinkering with is

public class TwoThingsIPC<T> where T : IPassClass
{ ...
}

where IPassClass is an interface.

Code from a third-party that I am using has the format

public class TwoThingsIPC<IPassClass>
{ ...
}

Both result in the same behaviour in my code, but are they the same and if not what is the difference?

like image 992
Stephan Luis Avatar asked Feb 25 '14 21:02

Stephan Luis


1 Answers

They are not the same. The second declaration is misleading:

public class TwoThingsIPC<IPassClass>
{ ...
}

does not constrain the type to the IPassClass interface. It uses a poor choice of names for a generic argument. There's nothing preventing you from creating an instance of TwoThingsIPC<int> - the IPassClass references in the class's code would just be "replaced" by int.1

On the other hand, a variable of type TwoThingsIPC<IPassClass>, for example:

TwoThingsIPC<IPassClass> myVar = new TwoThingsIPC<IPassClass>();

does constrain the type to the IPassClass interface.


1 That's not what really happens, but I don't have a better explanation yet.

like image 134
D Stanley Avatar answered Nov 16 '22 01:11

D Stanley