tags:

views:

128

answers:

4

I took this from Jon Skeet's "C# in depth".

He mentioned the following is valid

(1) class Sample<T> where T:class,Stream

and the following is invalid

(2) class Sample<T> where T:Stream,class

what is the reason for the second one being invalid?

+9  A: 

I think that the type constraint by value (struct) or reference (class) has to be at first place, just like the new constraint has to be the last if they are more than one.

Also the constraint by itself doesn't make much sense, Stream is a class, T will be a reference type (class) only by that constraint, so basically it's quite redundant.

CMS
+2  A: 

A "class or "struct" constraint must come before any other constraint when using Where. best,

BillW
+6  A: 

It is mentioned in the C# Language Specification, chapter 10.1.5:

The list of constraints given in a where clause can include any of the following components, in this order : a single primary constraint, one or more secondary constraints, and the constructor constraint, new(). A primary constraint can be a class type or the reference type constraint class or the value type constraint struct. A secondary constraint can be a type-parameter or interface-type.

I bolded the relevant phrase.

Hans Passant
+4  A: 

In fact, the author is mistaken.

class Sample<T> where T : class, Stream, new()

(which is the supposedly valid example given) is invalid too, because it's redundant. If T derives from Stream (which is a class) then it's clearly going to be a reference type.

The second example is also invalid, but this time because the class/struct constraint has to come first (like the constructor constraint has to come last).

There are rumours that this is fixed in the second edition. Sources close to the author indicate that the first example may have been changed to:

class Sample<T> where T : class, IDisposable, new()

Personally I think it's shocking that a mistake such as this made it past the technical reviewer for the first edition ;)

Jon Skeet
Hi Jon, It is good, Sir, to know you are "mortal," since I am still so ensorcelled by "C# in Depth" (which I don't pretend to [but aspire to] understand) that my synapses resulting from forty years of technical proofreading experience have yet to quiver and send the "errata" exception up to the BMCL (Base Morphemic Class Library) :) best,
BillW