string s1; string s2 = null; if (s1 == null) // compile error if (s2 == null) // ok
I don't really understand why the explicit assignment is needed. Whats the difference between a null variable and an unassigned variable? I always assumed that unassigned variables were simply assigned as null by the runtime/compiler anyway. If they're not null, then what are they?
A variable can be explicitly assigned NULL or its value been set to null by using unset() function.
null is a way to assign nothing to a variable. It can be used for default values or if something is just missing.
We cannot assign null to primitive variables e.g int, double, float, or boolean. If we try to do so, then the compiler will complain. The java instanceof operator which is also known as type comparison operator, tests whether the object is an instance of the specified type (class or subclass or interface).
In C#, there exist two types of variables which are value types and reference types. Value type variables cannot be assigned null, whereas we can assign null to reference type variables. As the string is a reference type, it can be null.
Unassigned members are automatically initialized to their default values (which is the null reference in the case for string
).
Unassigned local variables are not assigned any value and trying to access a possibly unassigned variable will give a compile error.
The reason why explicit assignment is required is quite simple. This often a source of errors when people try to use unassigned/uninitialized variables.
By forcing the developer to do this, it eliminates errors which happen when the developer forgets to initialize the variable. And by initializing it, you're in control of it.
It's a good thing really! I dunno how often I had uninitialized or undefined variables in some of the scripting languages which took quite some time to be found ^^
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