Value types and null value paradigm
A reference is null when it does not reference any object. This is the default value taken by all references. You just need to have a glance at the code of any application to notice that developers commonly take advantage of null references. In general, the use of a null reference allows communicating some information.
A method which must return a reference to an object returns a null reference to indicate that the requested object cannot be found. This relieves developers from having to implement a binary error code.
When you encounter a method which accepts an argument of a reference type which can be null,this argument is generally optional.
A field of a reference type which is null can be used to indicate that the object is being initialized, updated or even deleted and that it does not have a valid state. The notion of nullness is also commonly used within relational databases to indicate that a value in a record is not assigned. This notion can also be used to designate an optional attribute in an XML element.
Amongst the several differences between the value and reference types, we can take a look at the fact that the notion of nullness doesn't exist for value type. This generally causes several problems. For example, how to interpret a null integer value (or not yet assigned) retrieved from a database or from an XML document? Multiple solutions exist but none are fully satisfying:
We create a wrapper class containing an integer field. Here, the disadvantage is that in addition to having to maintain a new class, we add a significant burden to the garbage collector by creating several small objects on the heap.
If the whole range of integer values is not usable, we create a convention. For example, a null integer value is represented by an integer equal to 0 or 1. The several disadvantages to this approach are evident: constraint to maintain everywhere in the code, possibility of changes in the range of values taken by this field...
We use boxing, for example by casting our integer value into a reference of type object. In addition to not being type-safe, this solution also has the disadvantage of overloading the garbage collector.
We create a wrapper structure containing two fields, an integer and a boolean, that is set to false,means that we have a null value. Here, we must manage an additional structure for value type and an additional state for each value.
To deal with this recurring problem, the designers of C#2/.NET2 decided to provide the concept of nullable types.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|