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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With