zhusp
zhusp

Reputation: 183

Why can't I use a ValueType[] extension method

I can use a ValueType extension method with

public static string ToStringN(this ValueType value)
{
    return Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture);
}

But I can't use an extension method of a ValueType array.

public static void FastReverse(this ValueType[] arr)
{
    for (int i = 0; i < arr.Length / 2; i++)
    {
        ValueType tmp = arr[i];
        arr[i] = arr[arr.Length - i - 1];
        arr[arr.Length - i - 1] = tmp;
    }
}

Upvotes: 1

Views: 141

Answers (1)

Sweeper
Sweeper

Reputation: 271050

As you observed, this works:

public static string ToStringN(this ValueType value)
{
    return Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture);
}

// usage:
int a = 10;
a.toStringN();

This is because int is a ValueType, so whatever extension method a ValueType, int has it too.

However, if you do an extension method of a ValueType[],

public static void FastReverse(this ValueType[] arr)
{
    for (int i = 0; i < arr.Length / 2; i++)
    {
        ValueType tmp = arr[i];
        arr[i] = arr[arr.Length - i - 1];
        arr[arr.Length - i - 1] = tmp;
    }
}

// usage:
int[] a = {1,2,3};
a.FastReverse(); // Can't find this method!

This is because int[] and ValueType[] are not subtypes of each other. For example, this does not compile:

ValueType[] a = new int[10];

A workaround is to use generics and constraint the parameter to be struct:

public static void FastReverse<T>(this T[] arr) where T: struct
{
    for (int i = 0; i < arr.Length / 2; i++)
    {
        T tmp = arr[i];
        arr[i] = arr[arr.Length - i - 1];
        arr[arr.Length - i - 1] = tmp;
    }
}

This might not be exactly the behaviour you intended, as it does not work with int?[].

Upvotes: 2

Related Questions