News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

Overloading in c#

Started by OmMuruga, Feb 07, 2009, 01:38 PM

Previous topic - Next topic

OmMuruga

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.

alenfort

C # allows you to define different versions of a class method, the compiler will automatically select the most appropriate to provide a basis for the parameters is Overloading.

denniscrown

Operator overloading makes a program clearer than accomplishing the same operations with explicit method calls. Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

yagnesh

Operator overloading is claimed to be useful because it allows the developer to program using notation "closer to the target domain"[1] and allows user-defined types a similar level of syntactic support as types built into the language. It can easily be emulated using function calls; for an example, consider the integers a, b, c:
a + b * c
In a language that supports operator overloading, and assuming the '*' operator has higher precedence than '+', this is effectively a more concise way of writing:
add (a, multiply (b,c))
Time operator+(const Time& lhs, const Time& rhs) {
     Time temp = lhs;
     temp.seconds += rhs.seconds;
     if (temp.seconds >= 60) {
         temp.seconds -= 60;
         temp.minutes++;
     }
     temp.minutes += rhs.minutes;
     if (temp.minutes >= 60) {
         temp.minutes -= 60;
         temp.hours++;
     }
     temp.hours += rhs.hours;
     return temp;
}