test

Page 49

Another approach is to omit the type name after the new keyword, and have the compiler infer the array type. This is a useful shortcut when passing arrays as arguments. For example, consider the following method: void Foo (char[] data) { ... }

We can call this method with an array that we create on the fly, as follows: Foo ( new char[] {'a','e','i','o','u'} ); Foo ( new[] {'a','e','i','o','u'} );

// Longhand // Shortcut

This shortcut is essential in creating arrays of anonymous types, as we’ll see later.

Variables and Parameters A variable represents a storage location that has a modifiable value. A variable can be a local variable, parameter (value, ref, or out), field (instance or static), or array element.

The Stack and the Heap The stack and the heap are the places where variables and constants reside. Each has very different lifetime semantics.

Stack The stack is a block of memory for storing local variables and parameters. The stack logically grows and shrinks as a function is entered and exited. Consider the following method (to avoid distraction, input argument checking is ignored): static int Factorial (int x) { if (x == 0) return 1; return x * Factorial (x−1); }

This method is recursive, meaning that it calls itself. Each time the method is entered, a new int is allocated on the stack, and each time the method exits, the int is deallocated. Variables and Parameters | 35


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.