I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic.
In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance.
I believe that the best way to do that is creating a generic type here. But how can I do that using arrays?
Thanks!!!
public static class MyExtensions
{
public static int GetLastIndex(this byte[] buffer)
{
return buffer.GetUpperBound(0);
}
}
Generics in extension methods aren’t really anything special, they behave just like in normal methods.
As per your comment, you could do something like the following to effectively restrict the type of
T(adding guard statements).Note: As Martin Harris pointed out in a comment, you don’t actually need to use generics here. The
Arraytype from which all arrays derive will suffice.If you want a more elegant solution, at the cost of slightly more code, you could just create overloads of the method: