Thursday, June 07, 2007

int[] = object OR object[]

Let ms share an interesting fact[compiler rule] of C# language, consider the following class …
class TestCSharpFacts
{
public void DoSomthing(object obj)
{
MessageBox.Show("Inside DoSomthing(object obj)" + obj.ToString());
}

public void DoSomthing(object[] obj)
{
MessageBox.Show("Inside DoSomthing(object[] obj)" + obj.Length.ToString());
}
}

Now, say you are calling DoSomething method in the following way ..

1. obj.DoSomthing(123);

2. obj.DoSomthing(new System.Int32[] { 1, 2, 3 });

In the first case we all can say the first method will be called, but guess which routine will be called in the second case, it will again call the first method, i.e. DoSomthing(object obj),

Why does it happen ? My assumption is, C# consider a ‘Value’ type array as an ‘Object’ not an ‘Array of Object’, however an ‘Array of Reference’ is considered as ‘Array of Object’, so if we do a call like the following
TestCSharpFacts[] objs = new TestCSharpFacts[4];
obj.DoSomthing(objs);
C# will call the second method.

So, the rule is
a) Value type array = Object
b) Reference type array = Object[]

However, I am yet to find any Microsoft documentation on this, I am looking around for it.

1 comment:

Neo said...

I have posted this issues in the "C# User community" and got the answer from from David Browne a Technology Architect of Microsoft Corp.

Here is the answer ....
The overload resolution picks DoSomething(object) because no implicit conversion exists from an array of value types to an array of object.

See:

Array covariance specifically does not extend to arrays of value-types. For example, no conversion exists that permits an int[] to be treated as an object[].
http://msdn2.microsoft.com/en-us/library/aa664572(VS.71).aspx