A function member contains executable code that performs work for the class. The following are examples of function members in C#:
□ Methods
□ Properties
□ Events
□ Indexers
□ User-defined operators
□ Constructors
□ Destructors
Events and indexers are covered in detail in Chapters 7 and 13.
Methods
In C#, every function must be associated with a class. A function defined with a class is known as a method. In C#, a method is defined using the following syntax:
[access_modifiers] return_type method_name(parameters) {
//---Method body---
}
Here's an example — the ValidateEmail()
method defined in the Contact
class:
public class Contact {
public static ushort MAX_EMAIL;
public int ID;
public string FirstName;
public string LastName;
public string Email;
public Boolean ValidateEmail() {
//---implementation here---
Boolean valid=true;
return valid;
}
}
If the method does not return a value, you need to specify the return type as void
, as the following PrintName()
method shows:
public class Contact {
public static ushort MAX_EMAIL;
public int ID;
public string FirstName;
public string LastName;
public string Email;
public Boolean ValidateEmail() {
//---implementation here---
//...
Boolean valid=true;
return valid;
}
public void PrintName() {
Console.WriteLine("{0} {1}", this.FirstName, this.LastName);
}
}
Passing Arguments into Methods
You can pass values into a method using arguments. The words parameter and argument are often used interchangeably, but they mean different things. A parameter is what you use to define a method. An argument is what you actually use to call a method.
In the following example, x and y are examples of parameters:
public int AddNumbers(int x, int y) {}
When you call the method, you pass in values/variables. In the following example, num1
and num2
are examples of arguments:
Console.WriteLine(AddNumbers(num1, num2));
Consider the method named AddNumbers()
with two parameters, x
and y
:
public int AddNumbers(int x, int y) {
x++;
y++;
return x + y;
}
When you call this method, you also need to pass two integer arguments ( num1
and num2
), as the following example shows:
int num1 = 4, num2 = 5;
//---prints out 11---
Console.WriteLine(AddNumbers(num1, num2));
Console.WriteLine(num1); //---4 ---
Console.WriteLine(num2); //---5---
In C#, all arguments are passed by value by default. In other words, the called method gets a copy of the value of the arguments passed into it. In the preceding example, for instance, even though the value of x
and y
are both incremented within the method, this does not affect the values of num1
and num2
.
If you want to pass in arguments to methods by reference, you need to prefix the parameters with the ref
keyword. Values of variables passed in by reference will be modified if there are changes made to them in the method. Consider the following rewrite of the AddNumbers()
function:
public int AddNumbers(ref int x, ref int y) {
x++;
y++;
return x + y;
}
Because C# functions can only return single values, passing arguments by reference is useful when you need a method to return multiple values.
In this case, the values of variables passed into this function will be modified, as the following example illustrates:
int num1 = 4, num2 = 5; //---prints out 11---
Console.WriteLine(AddNumbers(ref num1, ref num2));
Console.WriteLine(num1); //---5---
Console.WriteLine(num2); //---6---
After calling the AddNumbers()
function, num1
becomes 5 and num2
becomes 6. Observe that you need to prefix the arguments with the ref
keyword when calling the function. In addition, you cannot pass literal values as arguments into a method that requires parameters to be passed in by reference:
//---invalid arguments---
Console.WriteLine(AddNumbers(4, 5));
Also note that the ref
keyword requires that all the variables be initialized first. Here's an example:
public void GetDate(ref int day, ref int month, ref int year) {
day = DateTime.Now.Day;
month = DateTime.Now.Month;
year = DateTime.Now.Year;
}
The GetDate()
method takes in three reference parameters and uses them to return the day, month, and year.
If you pass in the day, month and year reference variables without initializing them, an error will occur:
//---Error: day, month, and year not initialized---
int day, month, year;
GetDate(ref day, ref month, ref year);
If your intention is to use the variables solely to obtain some return values from the method, you can use the out
keyword, which is identical to the ref
keyword except that it does not require the variables passed in to be initialized first:
public void GetDate(out int day, out int month, out int year) {
day = DateTime.Now.Day;
month = DateTime.Now.Month;
year = DateTime.Now.Year;
}
Also, the out
parameter in a function must be assigned a value before the function returns. If it isn't, a compiler error results.
Like the ref
keyword, you need to prefix the arguments with the out
keyword when calling the function:
int day, month, year;
GetDate(out day, out month, out year);
The this Keyword
The this
keyword refers to the current instance of an object (in a nonstatic class; discussed later in the section Static Classes). In the earlier section on methods, you saw the use of this
:
Console.WriteLine("{0} {1}", this.FirstName, this.LastName);
While the FirstName
and LastName
variable could be referenced without using the this
keyword, prefixing them with it makes your code more readable, indicating that you are referring to an instance member.
However, if instance members have the same names as your parameters, using this
allows you to resolve the ambiguity:
public void SetName(string FirstName, string LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
Another use of the this
keyword is to pass the current object as a parameter to another method. For example:
Читать дальше