Saturday, February 7, 2009

Overloading in C#

Overloading
Sometimes it may be useful to have two functions that do the same thing but take different parameters.This is especially common for constructors, when there may be several ways to create a new instance.
class Point
{
// create a new point from x and y values
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
// create a point from an existing point
public Point(Point p)
{
this.x = p.x;
this.y = p.y;
}
int x;
int y;
}
class Test
{
public static void Main()
{
Point myPoint = new Point(10, 15);
Point mySecondPoint = new Point(myPoint);
}
}
The class has two constructors; one that can be called with x and y values, and one that can be called with another point. The Main() function uses both constructors; one to create an instance from an x and y value, and another to create an instance from an already-existing instance.
When an overloaded function is called, the compiler chooses the proper function by matching the
parameters in the call to the parameters declared for the function.

No comments:

Post a Comment