Why is C # by default irrelevant for unrecognized local variables?

Let's say I have something like this:

public IOrder SomeMethodOnAnOrderClass() { IOrder myOrder = null; if (SomeOtherOrder != null) { myOrder = SomeOtherOrder.MethodThatCreatesACopy(); } return myOrder; } 

Why did C # creators require an explicit set from myOrder to null ?

Is there ever a time when you want to leave it unassigned?

Does the null parameter value have a value associated with this? So that you do not want variables that are not assigned to zero to be always assigned? (Even if they are later installed on something else.)

Or do you need to make sure that you "dotted all of your selves and crossed all of your t"?

Or is there another reason?

+6
source share
2 answers

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

This is a function. In the wild, there are all kinds of errors caused by programmers using uninitialized variables. Not all languages ​​give you such well-defined behavior for these kinds of things (you know who you are ...).

Apparently, you have not experienced this yet. Be happy and agree that the compiler helps you write better code.

+9
source

Q Why are local variables specifically assigned to unreachable statements? (thanks, MiMo for reference) Eric Lippert says:

The reason we want to make it illegal is not the way many people believe, because the local variable will be initialized by garbage, and we want to protect you from garbage. We really automatically initialize locals by default. (Although C is not a C ++ programming language, it will be fun to read garbage from an uninitialized local one.) Rather, it is because the existence of such a code path is probably a mistake, and we want to throw you in the quality pit; You will have to work hard to write that error.

As far as I understand, if a local variable is not assigned a value, this does not mean that the developer really wanted to get default(T) when reading from it. This means (in most cases) that the developer probably skipped it and forgot to initialize it. This is more of a mistake, and then a situation where the developer consciously wants to initialize a local variable to default(T) by simply declaring it.

+4
source

All Articles