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();
Learn a new thing thanks Nish