This is due to the difference between Value Types and Reference Types .
"A data type is a value type if it contains data within its own memory allocation." whereas "Link type contains a pointer to another memory cell in which data is stored."
Common examples of value types:
- All numeric data types
- Boolean, Char and Date
- All structures, even if their elements are reference types
- Enumerations, since their base type is always SByte, Short, Integer, Long, Byte, Short, UInteger, or ULong
Common examples of reference types:
- Line
- All arrays, even if their elements are value types
- Class types such as Form
- Delegates
All value types are initialized to the default value (zero for numeric types), and reference types indicate null .
Ad:
int num;
Does not initialize the num variable. Therefore, num cannot be used. C # requires that each variable be set to some value (be it null or a number) before using it.
The same applies to reference types:
However, the announcement:
int[] numbers = new int[5];
It calls the initialization of the array (therefore, calls the constructor of the array), which then calls the initialization of each of the default elements for the int value (i.e., zero).
Using the same method in a reference type gives the same result:
string[] strings = new string[5];
Invokes array initialization and, therefore, creates a null string array (which is the default value for all types of links).
Structures are the data type you are looking for. Structures are value types and therefore cannot be set to null . Since they cannot be set to null , they must have a specific default value. The default value is determined by the default constructor .
The structure can be defined as follows:
struct MyStructName {
This will determine the data type that contains the members, myNumber and myString, which cannot be set to null .
//Array of MyStructName, the default constructor is called and each value is initialized MyStructName[] data = new MyStructName[5]; //Loop and print results for(int i = 0; i < data.Length; i++) { //Prints the index, number and the string or "null" Console.WriteLine("{0}: myNumber: {1}, myString: \"{2}\"", i, data[i].myNumber, data[i].myString != null ? data[i].myString : "null"); }