Variables and Parameters
A variable represents a typed storage location. A variable can be a local variable, parameter, array element, an instance field, or a static field.
All variables have an associated type, which essentially defines the possible values the variable can have and the operations that can be performed on that variable. C# is strongly typed, which means the set of operations that can be performed on a type are enforced at compile time, rather than at runtime. In addition, C# is type-safe, which ensures that a variable can be operated on only via the correct type with the help of runtime checking (except in unsafe blocks; see Section 4.8 in Chapter 4).
Definite Assignment
All variables in C# (except in unsafe contexts) must be assigned a value before they are used. A variable is either explicitly assigned a value or automatically assigned a default value. Automatic assignment occurs for static fields, class instance fields, and array elements not explicitly assigned a value. For example:
using System; class Test { int v; // Constructors that initalize an instance of a Test public Test( ) { } // v will be automatically assigned to 0 public Test(int a) { // explicitly assign v a value v = a; } static void Main( ) { Test[ ] tests = new Test [2]; // declare array Console.WriteLine(tests[1]); // ok, elements assigned to null Test t; Console.WriteLine(t); // error, t not assigned before use } }
Default Values
Essentially the default value for all primitive (or atomic) types ...
Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.