.NET 2.0, Generics and Math

Wanted to try generics support in Mono, and write a simple matrix class. Sounds pretty easy, but soon I noticed, it wasn't. The are no constraints for operators, and so how does the compiler now if something like

public class Calculator {	public T Add(T val1, T val2) {		return val1 + val2;	}}

is valid? So it throws an error. Looking through the MSDN Library and such I found no obvious solution to this problem, but Google eventually found me this very good article at The Code Project. The proposed solution is not the simplest one, but has (when the compiler is goof enough) no performance drawback, is quite transparent to the user of the generic class, and the downloadable code supplied with the article does much of the work anyway.

Oh, and by the way, I found to other articles at MSDN, which are wort a read: Introduction to C# generics and Create Elegant Code with Anonymous Methods, Iterators, and Partial Classes.

Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>