I am a little confused about null values and variables in .NET. (VB preferred)
Is there any way to check the "nullness" of ANY given variable regardless of whether it was an object or a value type? Or does my null check have to always anticipate whether it's checking a value type (e.g. System.Integer) or an object?
I guess what I'm looking for is a function that checks all possible kind of null-ness. That is, any type of variables that
a) were never assigned a value since declared
b) were assigned a null value from a data object (that came from a database)
c) were set equals to another variable value which was null
d) were set to an ASP.NET session/application variable that was never set or expired.
Is there a general best-practice when it comes to handling null scenarios in .NET?
UPDATE: When I talk about a value type being "null", what I really mean is a value type that was either never set or was at some point set equal to or cast from a null object.
Normal value types (booleans, ints, longs, float, double, enum and structs) are not nullable.
The default value for all value types is 0.
The CLR won't let you access variables unless they have been set. You may think this isn't always the case, but sometimes the CLR steps in and initializes them for you. At a method level you must explicitly initialize all variables before they are used.
Further, as others point out, since .net 2.0 there is a new generic type called
Nullable<T>. There are some compiler shorthands in C# like int? means
Nullable<int>, double? means
You can only wrap
Nullable<T> over non-nullable value types, which is fine since references already have the ability to be null.
int? x = null;
For an int?, while you can test against null, it's sometimes nicer to call
In C# there's also the nullable coalescing operator ?? when you want to assign a nullable to a non-nullable value type. But if you don't have the operator, you can call GetValueOrDefault().
int y = x ?? 2; // y becomes 2 if x is null. int z = x.GetValueOrDefault(2); // same as y