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
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.
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.
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.
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With