Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit assignment of null

Tags:

c#

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?

like image 923
fearofawhackplanet Avatar asked Oct 08 '10 11:10

fearofawhackplanet


People also ask

How do you assign to null?

A variable can be explicitly assigned NULL or its value been set to null by using unset() function.

What is the purpose of assigning a null value?

null is a way to assign nothing to a variable. It can be used for default values or if something is just missing.

Can we assign null?

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).

Can you assign null to string?

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.


2 Answers

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.

like image 87
Mark Byers Avatar answered Oct 04 '22 04:10

Mark Byers


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 ^^

like image 25
Tseng Avatar answered Oct 04 '22 02:10

Tseng