msdn.com/ericlippert/
archive/tags/Covariance+and+Contravariance/default.aspx.
This limitation is a very common cause of questions on C# discussion groups. The
remaining issues are either relatively academic or affect only a moderate subset of the
development community. The next one mostly affects those who do a lot of calculations
(usually scientific or financial) in their work.
3.6.2 Lack of operator constraints or a ???numeric??? constraint
C# is not without its downside when it comes to heavily mathematical code. The need
to explicitly use the Math class for every operation beyond the simplest arithmetic and
the lack of C-style typedefs to allow the data representation used throughout a program
to be easily changed have always been raised by the scientific community as barriers
to C#??™s adoption. Generics weren??™t likely to fully solve either of those issues, but
there??™s a common problem that stops generics from helping as much as they could
have. Consider this (illegal) generic method:
public T FindMean
(IEnumerable data)
{
T sum = default(T);
int count = 0;
foreach (T datum in data)
{
sum += datum;
count++;
}
107 Limitations of generics in C# and other languages
return sum/count;
}
Obviously that could never work for all types of data??”what could it mean to add one
Exception to another, for instance? Clearly a constraint of some kind is called for??¦
something that is able to express what we need to be able to do: add two instances of T
together, and divide a T by an integer.
Pages:
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229