Thursday, 15 August 2013

Confusion about NullReferenceException

Confusion about NullReferenceException

As far as I know Console.WriteLine() (or Console.Write()) calls object's
ToString() method to get the string represantation of the object right ?
So those two calls to Console.WriteLine() are the same right ?
Foo foo = new Foo();
Console.WriteLine(foo); // This is same as the one bellow
Console.WriteLine(foo.ToString());
So lets assume the following situation. I declare an instantiate an array
of Foos.
Foo[] foos = new Foo[10]; // After this line all 10 Foos are `null`s
Then I call the Console.WriteLine() on any element of the array without
instantiating the Foos itself. So in this case we have an array of Foos
and every Foo in the array is null so the call to the Console.WriteLine()
should cause a NullReferenceException to be thrown right ? But the things
is if you call it like this
Console.WriteLine(foos[0])
nothing happens except for the Environment.NewLine being written in the
console window but if you call it like this
Console.WriteLine(foos[0].ToString())
it actually throws a NullReferenceException. What is the difference
between those two calls? I mean in first one I don't call ToString()
explicitly but should not it be called implicitly by Console.WriteLine()
anyway ? And how does the NullReferenceException is not thrown in the
first case ?

No comments:

Post a Comment