Alex Rivera | Logout

How do I write an extension method for a generic type with constraints on type parameters?

Asked 2011-02-08T01:49:11.157
15

I'm working with a task specific .NET plattform, which is precompiled and not OpenSource. For some tasks I need to extend this class, but not by inheriting from it. I simply want to add a method.

At first I want to show you a dummycode existing class:

public class Matrix<T> where T : new() {
    ...
    public T values[,];
    ...
}

I want to extend this class in the following way:

public static class MatrixExtension {
    public static T getCalcResult<T>(this Matrix<T> mat) {
        T result = 0;
        ...
        return result;
    }
}

I've got this syntax from many google links so no idea whether it is correct. The compiler tells me no error, but in the end it doesn't work. In the end I want to call this function in the following way:

Matrix<int> m = new Matrix<int>();
...
int aNumber = m.getCalcResult();

So anyone got an idea? Thank you for your help!

Regards Nem

Edit
Report

1 Answer

2

Right now, the only "error" I'd see is this:

T result = 0;

You could change that to:

T result = default(T);

In the case of value types, this will be zero, so it would be safe.

However, you're going to find that this is difficult when you get to the "..." section you've listed. The basic types (int, double, etc) don't implement a method you can use to compute your math. This is a long time, very highly voted request on Connect, btw.

While there are workarounds, they make life very difficult. Unlike templates in C++, C#'s generics really don't support type safe mathematical operations on arbitrary types.

answered 2011-02-08T02:04:51.910

Your Answer