Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft C# Professional Projects - Premier Press.pdf
Скачиваний:
177
Добавлен:
24.05.2014
Размер:
14.65 Mб
Скачать

COMPONENTS OF C#

Chapter 3

55

 

 

 

sealed. A sealed method is used with an override method to override an inherited virtual method. However, a class inherited from the class containing this method cannot override a sealed method.

Overloading a Method

Method overloading in C# is similar to method overloading in C++. Overloading a method allows you to declare more than one method with the same name in the same class. However, it is required that all methods with the same name take a different number of parameters or have different parameter types. The methods with the same name are called overloaded methods.

Defining Overloaded Methods

Method overloading is useful when you need to perform the same operation on different parameters. For example, you can overload a method Add() to add two integer numbers and two strings. Look at overloading a method with this example:

public int Add (int x, int y)

{

int z = x + y; return z;

}

public string Add (string string1, string string2)

{

string string3 = string1 + string2; return string3;

}

You will notice that both the methods have the same name, Add(). However, the first Add() method is used to add two integers, x and y, and return an integer z. The second Add() method adds two strings, string1 and string2, and returns a

string type string3.

Calling Overloaded Methods

After declaring a method, you need to call the method. When you call an overloaded method, the C# compiler needs to identify the method that is called. The C# compiler identifies the method based on the type of parameters passed in the method call statement.