
18 Structs
18.3 Class and struct differences
18.3.4 Default values
Paragraph 11 As described in §12.2, several kinds of variables are automatically initialized to their default value when they are created. 2 For variables of class types and other reference types, this default value is null. 3 However, since structs are value types that cannot be null, the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null. [Example: Referring to the Point struct declared above, the example Point[] a = new Point[100];initializes each Point in the array to the value produced by setting the x and y fields to zero. end example] Paragraph 21 The default value of a struct corresponds to the value returned by the default constructor of the struct (§11.1.1). 2 Unlike a class, a struct is not permitted to declare a parameterless instance constructor. 3 Instead, every struct implicitly has a parameterless instance constructor, which always returns the value that results from setting all value type fields to their default value and all reference type fields to null. [Note: Structs should be designed to consider the default initialization state a valid state. In the example
using System;
struct KeyValuePair
{
string key;
string value;
public KeyValuePair(string key, string value) {
if (key == null || value == null) throw new ArgumentException();
this.key = key;
this.value = value;
}
}
the user-defined instance constructor protects against null values only where it is explicitly called. In cases where a KeyValuePair variable is subject to default value initialization, the key and value fields will be null, and the struct must be prepared to handle this state. end note]
| |
| Jagger Software Ltd | |
| Company # 4070126 | |
| VAT # 762 5213 42 |