X hits on this document





29 / 396


object[] args = new object[3]; args[0] = x; args[1] = y; args[2] = z; Console.WriteLine("x={0} y={1} z={2}", args); Method body and local variables

A method’s body specifies the statements to execute when the method is invoked.

A method body can declare variables that are specific to the invocation of the method. Such variables are called local variables. A local variable declaration specifies a type name, a variable name, and possibly an initial value. The following example declares a local variable i with an initial value of zero and a local variable j with no initial value.

using System;

class Squares { static void Main() { int i = 0; int j; while (i < 10) { j = i * i; Console.WriteLine("{0} x {0} = {1}", i, j); i = i + 1; } } }

C# requires a local variable to be definitely assigned before its value can be obtained. For example, if the declaration of the previous i did not include an initial value, the compiler would report an error for the subsequent usages of i because i would not be definitely assigned at those points in the program.

A method can use return statements to return control to its caller. In a method returning void, return statements cannot specify an expression. In a method returning non-void, return statements must include an expression that computes the return value. Static and instance methods

A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only access static members.

A method declared without a static modifier is an instance method. An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method.

The following Entity class has both static and instance members.

class Entity { static int nextSerialNo;

int serialNo;

public Entity() { serialNo = nextSerialNo++; }

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

Document info
Document views1405
Page views1405
Page last viewedMon Jan 23 03:35:25 UTC 2017