Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Nullable Value Types

In this chapter:

C#’s Support for Nullable Value Types...................................................... 443

C#’s Null-Coalescing Operator.................................................................. 446

The CLR Has Special Support for Nullable Value Types.............................. 447

 

As you know, a variable of a value type can never be null; it always contains the value type’s value itself. In fact, this is why they call these types value types. Unfortunately, there are some scenarios in which this is a problem. For example, when designing a database, it’s possible to define a column’s data type to be a 32-bit integer that would map to the Int32 data type of the Framework Class Li- brary (FCL). But a column in a database can indicate that the value is nullable. That is, it is OK to have no value in the row’s column. Working with database data by using the Microsoft .NET Framework can be quite difficult because in the common language runtime (CLR), there is no way to represent an Int32 value as null.

       
   
 
 

 

Here is another example. In Java, the java.util.Date class is a reference type, and therefore, a variable of this type can be set to null. However, in the CLR, a System.DateTime is a value type,

and a DateTime variable can never be null. If an application written in Java wants to communicate a date/time to a web service running the CLR, there is a problem if the Java application sends null because the CLR has no way to represent this and operate on it.

To improve this situation, Microsoft added the concept of nullable value types to the CLR. To understand how they work, we first need to look at the System.Nullable<T> structure, which is defined in the FCL.


Here is the logical representation of how the System.Nullable<T> type is defined.

 

[Serializable, StructLayout(LayoutKind.Sequential)] public struct Nullable<T> where T : struct {

 

// These 2 fields represent the state

private Boolean hasValue = false; // Assume null

internal T value = default(T); // Assume all bits zero

 

public Nullable(T value) { this.value = value; this.hasValue = true;

}

public Boolean HasValue { get { return hasValue; } } public T Value {

get {

if (!hasValue) {

throw new InvalidOperationException( "Nullable object must have a value.");

}

return value;

}

}

 

public T GetValueOrDefault() { return value; }

 

public T GetValueOrDefault(T defaultValue) { if (!HasValue) return defaultValue; return value;

}

 

public override Boolean Equals(Object other) { if (!HasValue) return (other == null);

if (other == null) return false; return value.Equals(other);

}

 

public override int GetHashCode() { if (!HasValue) return 0;

return value.GetHashCode();

}

 

public override string ToString() { if (!HasValue) return "";

return value.ToString();



}

 

public static implicit operator Nullable<T>(T value) { return new Nullable<T>(value);

}

 

public static explicit operator T(Nullable<T> value) { return value.Value;

}

}


As you can see, this class encapsulates the notion of a value type that can also be null. Because Nullable<T> is itself a value type, instances of it are still fairly lightweight. That is, instances can still be on the stack, and an instance is the same size as the original value type plus the size of a Boolean field. Notice that Nullable’s type parameter, T, is constrained to struct. This was done because reference type variables can already be null.

So now, if you want to use a nullable Int32 in your code, you can write something like this.

 

Nullable<Int32> x = 5; Nullable<Int32> y = null;

Console.WriteLine("x: HasValue={0}, Value={1}", x.HasValue, x.Value); Console.WriteLine("y: HasValue={0}, Value={1}", y.HasValue, y.GetValueOrDefault());

 

When I compile and run this code, I get the following output.

 

x: HasValue=True, Value=5 y: HasValue=False, Value=0

 


Date: 2016-03-03; view: 996


<== previous page | next page ==>
Nbsp;   Detecting the Use of a Custom Attribute Without Creating Attribute-Derived Objects | Nbsp;   C#’s Support for Nullable Value Types
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.008 sec.)