Generic arrays and casting to an object array

This question was posted recently on the CodeProject forums. The OP wanted to know why this code would not compile (I’ve simplified it):

private void FooInternal(object[] values)
{
}

private void Foo<T>(T[] values)
{
    FooInternal(values);
}

The error thrown is:

Error	2	Argument 1: cannot convert from 'T[]' to 'object[]'

The fix is to add a constraint:

private void Foo<T>(T[] values) where T:class
{
    FooInternal(values);
}

If you are wondering why that is needed, consider this code snippet:

struct S
{
}

static void Main(string[] args)
{
    object[] arr = new S[10];
}

That won’t compile either. The reason’s that each of those value type members need to be boxed into an object to get an object array, meaning it’s now a different array. Since that is not standard behavior for casts, the compiler will not automatically do that for you (which is a good thing). If you did it manually, this is what it’d look like:

object[] arr = new S[10].Cast<object>().ToArray();
Advertisements

One thought on “Generic arrays and casting to an object array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s