开发者

Can array and nullable types be used before they are declared?

I quote the following paragraphs from the book: The C# Programming Language Fourth Edition

C# supports single- and multi-dimensional arrays of any type. Unlike the types listed above, array types do not have to be declared before they can be used. Instead, array types are constructed by following a type name with square brackets. For example, int[] is a single-dimensional array of int, int[,] is a two-dimensional array of int, and int[][] is a single-d开发者_开发技巧imensional array of single-dimensional arrays of int.

and

Nullable types also do not have to be declared before they can be used. For each non-n ullable value type T there is a corresponding nullable type T?, which can hold an additional value null. For instance, int? is a type that can hold any 32 bit integer or the value null.

How to use array and nullable types without declaring them in advance?


Short answer

What those quotations are trying to say is that you don't have to "create" (or declare) array and nullable value types, in the same way you declare custom classes, in order to use them. They are already available as C# language features.

Long answer

If you want to declare an array of ints, simply do this:

int[] intArray = new int[5];

If you made a custom class, for example Foo, and you want to declare an array of Foo objects, the first quotation is saying that you don't have to write code to tell the compiler about an array type that can hold Foo objects; just do this and the compiler will figure out the rest:

Foo[] fooArray = new Foo[5];

Similarly, to create items of nullable value types simply append ? to the type:

int? nullableInt = null;

Additionally, the above is just syntactic sugar for the Nullable<T> struct:

Nullable<int> nullableInt = null;

Note that this only applies to value types (including structs), as all reference types (objects, delegates, etc) are nullable by default.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜