X hits on this document

995 views

0 shares

0 downloads

0 comments

277 / 396

C# LANGUAGE SPECIFICATION

Within an instance constructor or instance function member of a class, this is classified as a value. Thus, while this can be used to refer to the instance for which the function member was invoked, it is not possible to assign to this in a function member of a class.

Within an instance constructor of a struct, this corresponds to an out parameter of the struct type, and within an instance function member of a struct, this corresponds to a ref parameter of the struct type. In both cases, this is classified as a variable, and it is possible to modify the entire struct for which the function member was invoked by assigning to this or by passing this as a ref or out parameter.

11.3.7 Field initializers

As described in §‎11.3.4, the default value of a struct consists of the value that results from setting all value type fields to their default value and all reference type fields to null. For this reason, a struct does not permit instance field declarations to include variable initializers. This restriction applies only to instance fields. Static fields of a struct are permitted to include variable initializers.

The example

struct Point { public int x = 1;  // Error, initializer not permitted public int y = 1;  // Error, initializer not permitted }

is in error because the instance field declarations include variable initializers.

11.3.8 Constructors

Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead, every struct implicitly has a parameterless instance constructor which always returns the value that results from setting all value type fields to their default value and all reference type fields to null (§‎4.1.2). A struct can declare instance constructors having parameters. For example

struct Point { int x, y;

public Point(int x, int y) { this.x = x; this.y = y; } }

Given the above declaration, the statements

Point p1 = new Point();

Point p2 = new Point(0, 0);

both create a Point with x and y initialized to zero.

A struct instance constructor is not permitted to include a constructor initializer of the form base(...).

If the struct instance constructor doesn’t specify a constructor initializer, the this variable corresponds to an out parameter of the struct type, and similar to an out parameter, this must be definitely assigned (§‎5.3) at every location where the constructor returns. If the struct instance constructor specifies a constructor initializer, the this variable corresponds to a ref parameter of the struct type, and similar to a ref parameter, this is considered definitely assigned on entry to the constructor body. Consider the instance constructor implementation below:

264Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views995
Page views995
Page last viewedFri Dec 09 09:56:53 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments