Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 996
Christoph Meißner Avatar asked Feb 08 '11 01:02

Christoph Meißner


People also ask

How do you add generic constraints?

You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

Which of the following generic constraints restricts the generic type parameter to an object of the class?

Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.


1 Answers

You need to add the same type parameter constraints on the extension method.

This is my attempt at the closest reconstruction of your example that compiles and runs, without any error:

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


 public static class MatrixExtension {
     public static T getCalcResult<T>(this Matrix<T> mat)  where T : new() {
         T result = new T();
         return result;
     }
 }

 class Program {
     static void Main(string[] args)  {
        Matrix<int> m = new Matrix<int>();
        int aNumber = m.getCalcResult();
        Console.WriteLine(aNumber); //outputs "0"
 }
like image 130
Mark Cidade Avatar answered Oct 14 '22 01:10

Mark Cidade