This is a mirror of official site: http://jasper-net.blogspot.com/

Different Kinds of Operator Overloading

| Sunday, October 24, 2010
What is Operator Overloading?

We know that standard data types supplied by languages are well known and there will be operators like +,* ,% operates on these data types. But, what is the case if it is user-defined types say a 3dpoint class, which is the combination of three integers. Well, all languages that supports operator overloading says, “It is your Type. Please you say how the operator + should work”.

If you say “How the Operator + should work for 3point class”, then the you are overloading the + operator. Because, it will now know how to add two integer and how to add two 3dpoint.

Below are the types of overloading that I will demonstrate in this article:

Implicit Conversion Operator
Explicit Conversion Operator
Binary Operator

Let us start with TimeHHMMSS class

Before we move on to the Overloading, first let me explain what this class will do. The class is used to store the time in Hour, Minute and Seconds. There are three members defined for that. The class Looks Like:

class TimeHHMMSS
{

//001: Parts of the time class
public int m_hour;
public int m_minute;
public int m_sec;

The default constructor will set all the members to zero. And a overloaded version will accept hour, minute and Seconds. Below is the code for Constructors:


//002: Default constructor for the class
public TimeHHMMSS()
{

m_hour = 0;
m_minute = 0;
m_sec = 0;
}

//003: Overloaded Construtor
public TimeHHMMSS(int hr, int min, int sec)
{

m_hour = hr;
m_minute = min;
m_sec = sec;
}

All classes in C# have Object as their base class. We will override the ToString method our own way.

//004: Every class that we create has Object as the base class. Override the ToString
public override string ToString()
{

return string.Format("{0}:{1}:{2}", m_hour, m_minute, m_sec);
}

Implicit Conversion – (A) Integer to TimeHHMMSS

Below is the Syntax for Implicit conversion:

public static implicit operator ( Variable)

We will get the integer as parameter. So the time is specified in smaller units say in seconds passed as an integer parameter. 1 Hour, 10 minutes, 15 Seconds can be specified in seconds as 4215. These “seconds” taken as an integer parameter is processed to split into Hour,Minutes,and Seconds. After the Split, we have all the member variable of the class is ready to return back. Below is the Conversion operator:

//005: Implicit Conversion Operator. Coversion from int to TimeHHMMSS
public static implicit operator TimeHHMMSS(int totalSeconds)
{

//005_1 : Declarations
int hour, min, seconds;
int RemainingSeconds;
TimeHHMMSS returnobject = new TimeHHMMSS();

//005_2: Calculate Seconds
seconds = totalSeconds % 60;
returnobject.m_sec = seconds;

Read more: Codeproject

Posted via email from .NET Info

0 comments: