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.