Reputation: 1051
I am trying to write a generic extension method for adding a fixed matrix to an "elastic" matrix. The extension method compiles and (I assume) its code works fine in a regular method. Knowing I'll be using this function a lot for various types, I would much prefer to figure this problem out instead of limping along with a band-aid:
public void AddMatrix<T>(this List<T[]> MyList, T[,] Matrix)
{
if (MyList == null) throw new ArgumentNullException("MyList");
if (Matrix == null) throw new ArgumentNullException("Matrix");
for (int i = 0; i < Matrix.GetLength(0); i++)
{
T[] aLine = new T[Matrix.GetLength(1)];
for (int j = 0; j < Matrix.GetLength(1); j++)
aLine[j] = Matrix[i, j];
MyList.Add(aLine);
}
}
public void testAddMatrix()
{
List<string[]> aMyBigMatrix = new List<string[]>();
string[,] aSmallerMatrix =
{
{
"foo",
"bar",
"what"
}
};
aMyBigMatrix.AddMatrix(aSmallerMatrix); // .AddMatrix is not showing up here in Intellisense?
}
Upvotes: 1
Views: 186
Reputation: 728
As everyone is quick to point out, extension methods must be static.
When I attempted to duplicate your error, I got a compiler error "Extension method must be static", so it seems strange to me that you report that your code compiles. When you try to compile it, look at the Error List to see if it is in fact empty. I suspect you will find an error message that you had not noticed before. If you are able to see the compiler errors, your mistakes of this nature will be easy to identify and fix.
Upvotes: 1
Reputation: 4849
Extension methods must be static.
Change it to: public static void AddMatrix(this List MyList, T[,] Matrix)
And make sure the class is static too.
Upvotes: 1
Reputation: 217293
From MSDN:
To defining and call the extension method
Define a static class to contain the extension method. The class must be visible to client code.
Implement the extension method as a static method with at least the same visibility as the containing class.
The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
Your method is not static (2.).
Upvotes: 4
Reputation: 61437
You are writing an extension method, AddMatrix<T>
needs to be static.
Upvotes: 1