Generics in extension methods aren't really anything special, they behave just like in normal methods.
public static int GetLastIndex<T>(this T[] buffer)
{
return buffer.GetUpperBound(0);
}
As per your comment, you could do something like the following to effectively restrict the type of T
(adding guard statements).
public static int GetLastIndex<T>(this T[] buffer) where T : struct
{
if (!(buffer is byte[] || buffer is ushort[] || buffer is uint[]))
throw new InvalidOperationException(
"This method does not accept the given array type.");
return buffer.GetUpperBound(0);
}
Note: As Martin Harris pointed out in a comment, you don't actually need to use generics here. The Array
type 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:
public static int GetLastIndex(this byte[] buffer)
{
return GetLastIndex(buffer);
}
public static int GetLastIndex(this ushort[] buffer)
{
return GetLastIndex(buffer);
}
public static int GetLastIndex(this uint[] buffer)
{
return GetLastIndex(buffer);
}
private static int GetLastIndex(Array buffer)
{
return buffer.GetUpperBound(0);
}