null and void

null and void

Two additional keywords relating to types are null and void.null is a literal value used to indicate that the data type (specifically, a reference type) is assigned nothing. void is used to indicate the absence of a type or the absence of any value altogether.


null can also be used as a type of string "literal." null indicates that a variable is set to nothing. Only reference types can be assigned the value null. The only reference type covered so far in this book is string; Chapter 5 covers the topic of reference types in detail. For now, suffice it to say that a reference type contains a pointer, an address, or a reference to a location in memory that is different from where the actual data resides. Code that sets a variable to null explicitly assigns the reference to point at nothing. In fact, it is even possible to check whether a reference type points to nothing. Listing 2.16 demonstrates assigning null to a string variable.

Listing 2.16. Assigning null to a String

static void Main() {     string faxNumber;     // ...     // Clear the value of faxNumber.     faxNumber = null;                                                            // ... } 

It is important to note that assigning the value null to a reference type is distinct from not assigning it at all. In other words, a variable that has been assigned null has still been set, and a variable with no assignment has not been set and therefore will often cause a compile error if used prior to assignment.

Assigning the value null to a string is distinctly different from assigning an empty string, "". null indicates that the variable has no value. "" indicates that there is a value: an empty string. This type of distinction can be quite useful. For example, the programming logic could interpret a faxNumber of null to mean that the fax number is unknown, while a faxNumber value of "" could indicate that there is no fax number.

The void Nontype

Sometimes the C# syntax requires a data type to be specified but no data is passed. For example, if no return from a method is needed C# allows the use of void to be specified as the data type instead. The declaration of Main within the HelloWorld program is an example. Under these circumstances, the data type to specify is void. The use of void as the return type indicates that the method is not returning any data and tells the compiler not to expect a value. void is not a data type per se, but rather, an identification of the fact that there is no data type.

Language Contrast: C++void Is a Data Type

In C++, void is a data type commonly used as void**. In C#, void is not considered a data type. Rather, it is used to identify that a method does not return a value.

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: