Nullable Types:
Nullable Types is a new concept (introduced in .Net 2.0), using which, a null value can be assigned to Value Types.
Nullable types concept is not vital for Reference Types as these can be initialized to null;
Nullable types are instances of the System.Nullable struct.
A nullable type can represent the normal range of values for its underlying value type, and an additional null value.
For example, If an integer is used along with nullable type, it can be assigned any value (defined in its range) and in addition it can be assigned a null value as well.
Nullable Types Basics:
Nullable types have the following characteristics:
Syntax:
T? value type
(It is shorthand for System.Nullable, where T is a value type. The two forms can be used in-interchange.)
T can be any value type including struct;but, cannot be a reference type.
Nullable Types Members:
Each instance of a nullable type has two public read-only properties:
- HasValue
HasValue is of type bool. If the variable contains a non-null value,It is set to true
- Value
Value is of the same type as the underlying type.
If HasValue is true, Value contains a meaningful value.
If HasValue is false, and Value is accessed, InvalidOperationException is thrown.
The default value for a nullable type variable sets HasValue to false. The Value is undefined
System.Nullable.GetValueOrDefault property is used to return either the assigned value or the default value for the underlying type if the value is null.
For example int j = x.GetValueOrDefault ();
.
Nested nullable types are not allowed. The following line will not compile:
Nullable> n;
Nullable Types Conversion:
Explicit Conversions
A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:
int? pp = null;
int nontcompile = pp
(Will not compile, null cannot be assigned to value type without using nullable types).
int compilewitherror = (int) pp;
(Compiles, throw exception if pp is null. Nullable object must have a value error is encountered at runtime)
int compilewitherror1= pp.Value;
(Compiles, throw exception if pp is null. Nullable object must have a value error is encountered at runtime)
Implicit Conversions
A variable of nullable type can be set to null with the null keyword, as shown below:
int? p1 = null;
The conversion from an ordinary type to a nullable type, is implicit.
int? x2;
x2 = 10; // Implicit conversion.
Operators
Any operator that exist for value types can used by nullable types.
These operators produce a null value if the operands are null;
If the values are not null, normal operation, as in case of value types is performed.
Let’s consider an example
Here we define two nullable types integer variable
int? a = 10;
int? b = null;
Now if a++ or a -- operation is performed, it will increment/decrement the value by 1.
Consider the addition a+b, here the result will be null, as b is null
A comparison of two nullable types which are both null will be evaluated to true, However if one of the nullable types is null, the comparison is always evaluated to be false.
?? Operator
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
A nullable type can contain a value, or it can be undefined.
The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type.
If a nullable type is assigned to a non-nullable type without using the ?? operator, compile-time error is generated. If a cast is used and the nullable type is currently undefined, an InvalidOperationException exception will be thrown.
Example:
protected void Page_Load(object sender, EventArgs e)
{
int? nullinterger = null;
int y = nullinterger ?? -1;
int nullordefault = GetNullableInt() ?? default(int);
string nullstring = GetStringValue();
Response.Write(nullstring ?? "Unspecified");
}
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
Code described above shows how ?? operator can be used.The vital point to understand here is, if left is null, right is the value and vice-versa.
The Following Code provides the implementation of the topics discussed here.
protected void Page_Load(object sender, EventArgs e)
{
//?? Operator Test
int? nullinterger = null;
int y = nullinterger ?? -1;
int nullordefault = GetNullableInt() ?? default(int);
string nullstring = GetStringValue();
Response.Write("?? Operator Result:"+" ");
Response.Write(nullstring ?? "Unspecified");
Response.Write("");
//Explicit Conversion TEst
//int k = nullinterger.Value;
//Will Thow exception, comment it to run the Code
// Response.Write(nullinterger.Value.ToString());
// implicit ConversionTest
int? p1 = null;
int? x2;
x2 = 10;
Response.Write("Implicit ConversionTest Result:"+" "+x2.ToString()+"");
//Operator Test
int? nonnull = 20;
nonnull = nonnull + nullinterger;
Response.Write("Operator Test Result:" + " " + nonnull.ToString() + "");
}
//Helper Methods
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
}
Gist: The Nullable Types add great functionality enhacements to the value types and can prove invaluable in database interaction code, where null value are used frequently.
Hope this article was Helpful.
Please don’t hesitate to comment on the article, does not matter even if it is a criticism as I believe in Continuous learning and your comments might add to it.
Comments
Post a Comment