VBForums >
.NET >
C# > [2.0] How to check for Null in a value type variable.
Click to See Complete Forum and Search --> : [2.0] How to check for Null in a value type variable.
bnathvbdotnet
May 13th, 2006, 08:12 AM
In a Value type variables like bool, int or float how to check if there is no value in that variable yet?
to check for a null in reference variable, we can check for null. Howz it possible for value types?
nath
wossname
May 13th, 2006, 08:30 AM
Value types are never null.
However, in .net 2005 there are Nullable types which means that you can asign null to virtually any value type...
int? i = null;
The "?" means that this integer is wrapped in an object that CAN be assigned null.
Personally I do not recommend these nulable types unless you are doing database work, they are slow (just like variants were in VB6).
jmcilhinney
May 13th, 2006, 08:33 AM
There's no such thing as a value type variable without a value. When you declare a variable it is created on the stack and each bit is set to zero. If the variable is a reference type then those zeroes represent null, i.e. the variable refers to no object on the heap. If the variable is a value type then those zeroes are interpreted as a value of that type. If the type is int then the value is 0, if the type is bool then the value is false, etc. If you try to test a value type for null you will get a compilation warning telling you that the test will always be false because a value type cannot be null. .NET 2.0 introduces the Nullable type to allow you to create value types variables that can be null:Nullable<int> i = null; ;
if (!i.HasValue)
{
MessageBox.Show("i has no value.");
}
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.