Prev | Current Page 162 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

You can see this discrepancy at
work when you use reflection to find the constructors of a value type??”
you won??™t see a parameterless one.
Again, let??™s look at a quick example, this time for a method. Just to show how it??™s useful,
I??™ll give the implementation of the method too.
public T CreateInstance() where T : new()
{
return new T();
}
This method just returns a new instance of whatever type you specify, providing
that it has a parameterless constructor. So CreateInstance(); and Create-
Instance(); are OK, but CreateInstance(); isn??™t, because string
doesn??™t have a parameterless constructor.
There is no way of constraining type parameters to force other constructor signatures
??”for instance, you can??™t specify that there has to be a constructor taking a single
string parameter. It can be frustrating, but that??™s unfortunately just the way it is.
Constructor type constraints can be useful when you need to use factory-like patterns,
where one object will create another one as and when it needs to. Factories often
need to produce objects that are compatible with a certain interface, of course??”and
that??™s where our last type of constraint comes in.
DERIVATION TYPE CONSTRAINTS
The final (and most complicated) kind of constraint lets you specify another type that
the type argument must derive from (in the case of a class) or implement (in the case
of an interface).


Pages:
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174