When a type parameter is constrained
to be a value type, comparisons using == and != are prohibited.
I rarely find myself using value or reference type constraints, although we??™ll see
in the next chapter that nullable types rely on value type constraints. The remaining
two constraints are likely to prove more useful to you when writing your own
generic types.
CONSTRUCTOR TYPE CONSTRAINTS
The third kind of constraint (which is expressed as T : new() and must be the last
constraint for any particular type parameter) simply checks that the type argument
used has a parameterless constructor, which can be used to create an instance. This
applies to any value type; any nonstatic, nonabstract class without any explicitly
declared constructors; and any nonabstract class with an explicit public parameterless
constructor.
77 Beyond the basics
NOTE C# vs. CLI standards??”There is a discrepancy between the C# and CLI
standards when it comes to value types and constructors. The CLI specification
states that value types can??™t have parameterless constructors, but
there??™s a special instruction to create a value without specifying any
parameters. The C# specification states that all value types have a default
parameterless constructor, and it uses the same syntax to call both explicitly
declared constructors and the parameterless one, relying on the compiler
to do the right thing underneath.
Pages:
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173