13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>C#</strong> LANGUAGE SPECIFICATIONclass Test{static void Main() {int i = 123;object o = i; // boxingint j = (int) o; // unboxing}}is more interesting. An int value can be converted to object and back again to int. This example showsboth boxing and unboxing. When a variable of a value type needs to be converted to a reference type, anobject box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite.When an object box is cast back to its original value type, the value is copied out of the box and into theappropriate storage location.This type system unification provides value types with the benefits of object-ness without introducingunnecessary overhead. For programs that don’t need int values to act like objects, int values are simply32-bit values. For programs that need int values to behave like objects, this capability is available ondemand. This ability to treat value types as objects bridges the gap between value types and reference typesthat exists in most languages. For example, a Stack class can provide Push and Pop methods that take andreturn object values.public class Stack{public object Pop() {…}}public void Push(object o) {…}Because <strong>C#</strong> has a unified type system, the Stack class can be used with elements of any type, includingvalue types like int.8.3 Variables and parametersVariables represent storage locations. Every variable has a type that determines what values can be stored inthe variable. Local variables are variables that are declared in methods, properties, or indexers. A localvariable is defined by specifying a type name and a declarator that specifies the variable name and anoptional initial value, as in:int a;int b = 1;but it is also possible for a local variable declaration to include multiple declarators. The declarations of aand b can be rewritten as:int a, b = 1;A variable must be assigned before its value can be obtained. The exampleclass Test{static void Main() {int a;int b = 1;int c = a + b; // error, a not yet assigned…}}results in a compile-time error because it attempts to use the variable a before it is assigned a value. Therules governing definite assignment are defined in §12.3.A field (§17.4) is a variable that is associated with a class or struct, or an instance of a class or struct. A fielddeclared with the static modifier defines a static variable, and a field declared without this modifierdefines an instance variable. A static field is associated with a type, whereas an instance variable isassociated with an instance. The example22

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!