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.

Chapter 8 <strong>Language</strong> Overviewusing Personnel.Data;class Employee{private static DataSet ds;public string Name;public decimal Salary;…}shows an Employee class that has a private static variable and two public instance variables.Formal parameter declarations also define variables. There are four kinds of parameters: value parameters,reference parameters, output parameters, and parameter arrays.A value parameter is used for “in” parameter passing, in which the value of an argument is passed into amethod, and modifications of the parameter do not impact the original argument. A value parameter refers toits own variable, one that is distinct from the corresponding argument. This variable is initialized by copyingthe value of the corresponding argument. The exampleusing System;class Test{static void F(int p) {Console.WriteLine("p = {0}", p);p++;}static void Main() {int a = 1;Console.WriteLine("pre: a = {0}", a);F(a);Console.WriteLine("post: a = {0}", a);}}shows a method F that has a value parameter named p. The example produces the output:pre: a = 1p = 1post: a = 1even though the value parameter p is modified.A reference parameter is used for “by reference” parameter passing, in which the parameter acts as an aliasfor a caller-provided argument. A reference parameter does not itself define a variable, but rather refers tothe variable of the corresponding argument. Modifications of a reference parameter impact thecorresponding argument. A reference parameter is declared with a ref modifier. The exampleusing System;class Test{static void Swap(ref int a, ref int b) {}}int t = a;a = b;b = t;static void Main() {int x = 1;int y = 2;}Console.WriteLine("pre: x = {0}, y = {1}", x, y);Swap(ref x, ref y);Console.WriteLine("post: x = {0}, y = {1}", x, y);shows a Swap method that has two reference parameters. The output produced is:23

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

Saved successfully!

Ooh no, something went wrong!