11

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?

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 2
    Because some types aren't nullable such as structs. The default value is equal to `default(IOrder)`. – Austin Brunkhorst Jan 23 '13 at 00:05
  • Related question: http://stackoverflow.com/questions/6213113/fixing-the-use-of-unassigned-local-variable-with-a-null-assignment-why – Despertar Jan 23 '13 at 00:06
  • 6
    Read [Eric Lippert's Absence of evidence is not evidence of absence](http://blogs.msdn.com/b/ericlippert/archive/2009/10/12/absence-of-evidence-is-not-evidence-of-absence.aspx) – horgh Jan 23 '13 at 00:08
  • 2
    See http://blogs.msdn.com/b/ericlippert/archive/2012/03/05/why-are-local-variables-definitely-assigned-in-unreachable-statements.aspx – MiMo Jan 23 '13 at 00:13
  • @MiMo +1: you specified the article actually answering the question. – horgh Jan 23 '13 at 00:16
  • @KonstantinVasilcov - that does not seem to say "Why". Just more of "what" and "how". (Of course I may not be understanding Eric. I sometimes have trouble fully understanding his posts.) – Vaccano Jan 23 '13 at 00:44
  • @MiMo - seem my previous comment (Only one @ user per comment) – Vaccano Jan 23 '13 at 00:44
  • possible duplicate of [About unassigned variables](http://stackoverflow.com/questions/14419175/about-unassigned-variables) – horgh Jan 23 '13 at 23:52

2 Answers2

11

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.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • 1
    True enough, except I think the question relates rather to why the compiler prevents you from using *local* variables which are not explicitly initialized. – RJ Lohan Jan 23 '13 at 00:19
  • As my example indicates, I was referring to local variables. Sorry, I should have been more clear. – Vaccano Jan 23 '13 at 00:38
  • I am kind of asking why what you describe does not happen for local variables. – Vaccano Jan 23 '13 at 00:41
  • @Vaccano: My answer is in reference to local variables. The reasoning is the same. It is good practice to initialize your variables. Code can change over time, and if you add some code in between the declaration and another chunk of code which assumed that the variable may be uninitialized before using it (but the new code does not), you may have a bug. C and C++ allow this (though you'll get a warning) and the value of an uninitialized variable is indeterminate (and reading an uninitialized variable results in UB). You can imagine how this can cause bugs. – Ed S. Jan 23 '13 at 04:34
8

In Why are local variables definitely assigned in unreachable statements? (thanks, MiMo for the link) Eric Lippert says:

The reason why we want to make this illegal is not, as many people believe, because the local variable is going to be initialized to garbage and we want to protect you from garbage. We do in fact automatically initialize locals to their default values. (Though the C and C++ programming languages do not, and will cheerfully allow you to read garbage from an uninitialized local.) Rather, it is because the existence of such a code path is probably a bug, and we want to throw you in the pit of quality; you should have to work hard to write that bug.

As far as I understand this, if a local variable is not assigned a value, it does not mean, that the developer indeed wanted to get the default(T) while reading from it. It means (in the majority of cases) that the developer probably missed it and forgot to initialize it. That is rather a bug, then a situation when a developer consciously wants to init a local variable to default(T) with just declaring it.

horgh
  • 17,918
  • 22
  • 68
  • 123
  • So it is a system to make sure you "dot your i's and cross your t's"? – Vaccano Jan 23 '13 at 00:40
  • 3
    @Vaccano: Correct; reading from an uninitialized local is almost certainly a mistake and so the compiler brings that to your attention rather than ignoring it. – Eric Lippert Jan 23 '13 at 00:44
  • But it is ok at the class level? (The class level gets a default, but locals don't) – Vaccano Jan 23 '13 at 00:45
  • @Vaccano locals do get the default values as well, however a compile-time error is generated if a local variable is not explicitly assigned. Why the same error is not generated for class fields, try asking Eric personally. You've got this opportunity thanks to his comment)) – horgh Jan 23 '13 at 00:58
  • [10.4.4 Field initialization](http://msdn.microsoft.com/en-us/library/aa645756%28v=vs.71%29.aspx) does say, that fields are automatically initialized to default values and thus are never uninitialized – horgh Jan 23 '13 at 00:59
  • @Vaccano: The above blog quote explains that locals "do in fact" get automatically initialised to their defaults. The difference is that you will get a compiler warning if your code doesn't _explicitly_ assign a value before otherwise using the local. Why the difference? I presume there's a great body of evidence that many more bugs are caused by uninitialised locals than by uninitialised fields. – groverboy Jan 23 '13 at 01:26
  • @EricLippert - So, why are the local variables assigned a default value then? (If it can never be used.) And why don't class level fields get the same treatment? (I would assume that it is too complex to catch in the compiler, but I thought I would ask any way.) – Vaccano Jan 23 '13 at 17:08
  • 3
    @Vaccano: See http://stackoverflow.com/questions/14419175/about-unassigned-variables/14419363#14419363 – Eric Lippert Jan 23 '13 at 19:35
  • @EricLippert - Thank You! Though that does not answer why locals get assigned to a default value if that value can never be used. – Vaccano Jan 23 '13 at 22:50
  • @Vaccano: "Use of unassigned local variable" is a C# language warning. It's the _runtime_ that assigns default values to locals, for code security, as explained here: http://stackoverflow.com/questions/753438/why-must-local-variables-have-initial-values/3383168#3383168 – groverboy Jan 24 '13 at 00:06
  • @groverboy it's not a warning, it is an error. While Vaccano asks, what this default value is assigned to a local variable for, if it's actually never read, as it will 100% be overwritten with the definite assignment at the very least. – horgh Jan 24 '13 at 00:12