null and voidTwo 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. nullnull 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
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 NontypeSometimes 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.
|