Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# default to null for unassigned local variables?

Tags:

c#

Say I have something like this:

public IOrder SomeMethodOnAnOrderClass()
{
   IOrder myOrder = null;

   if (SomeOtherOrder != null)
   {
       myOrder = SomeOtherOrder.MethodThatCreatesACopy();        
   }

   return myOrder;
}

Why did the makers of C# require the explicit set of myOrder to null?

Is there ever a case where you would want to leave it unassigned?

Does the setting to null have a cost associated with it? Such that you would not want to always have unassigned variables set to null? (Even if they are later set to something else.)

Or is it required to make sure you have "dotted all your i's and crossed all your t's"?

Or is there some other reason?

like image 793
Vaccano Avatar asked Jan 23 '13 00:01

Vaccano


1 Answers

They do default to null or, more accurately, your objects default to the value returned by default(T), which is different for value types.

This is a feature. There are all sorts of bugs in the wild caused by programmers using uninitialized variables. Not all languages give you such well defined behavior for this sort of thing (you know who you are...).

Apparently you haven't experienced that yet. Be happy and accept that the compiler is helping you to write better code.

like image 175
Ed S. Avatar answered Nov 15 '22 20:11

Ed S.