Skip Navigation Links

 CodeMatrixThe ultimate site for .NET programmers

Skip Navigation Links.    

Operator Overloading in C#

C# allows you to overload operators for use on your own classes. This makes it possible to define a user defined data type and to use as a fundamental data type. For example, you might create a new data type called StringCompare to represent a string, and provide methods that perform comparisions, such as using the == and != operators.

The following example demonstrates string comparision by overloading '==' and '!=' operators.

public class StringCompare
{
    private string firstString;
    private string secondString;

    public StringCompare(string string1, string string2)
    {
        firstString = string1;
        secondString = string2;
    }

    public static bool operator ==(StringCompare string1, StringCompare string2)
    {
        Console.WriteLine("In operator ==");
        //
        if ( (string1.firstString  == string2.firstString) &&
             (string1.secondString == string2.secondString))
        {
            return true;
        }
        return false;
    }

    public static bool operator !=(StringCompare string1, StringCompare string2)
    {
        Console.WriteLine("In operator !=");
        //
        if ( (string1.firstString == string2.firstString) &&
             (string1.secondString == string2.secondString))
        {
            return false;
        }
        return true;
    }

    public override bool Equals(object o)
    {
        Console.WriteLine("In method Equals");
        if (!(o is StringCompare))
        {
            return false;
        }
        return this == (StringCompare)o;
    }

    public override string ToString()
    {
        string s = firstString + " " + secondString;
        return s;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
}

class Program
{
    static void Main(string[] args)
    {
        StringCompare s1 = new StringCompare("Pat", "Weaver");
        Console.WriteLine("s1: {0}", s1.ToString());

        StringCompare s2 = new StringCompare("Kathy", "Smith");
        Console.WriteLine("s2: {0}", s2.ToString());

        if (s1 == s2)
        {
            Console.WriteLine("s1: {0} == s2: {1}", s1.ToString(), s2.ToString());
        }
        else
        {
            Console.WriteLine(s1.ToString() + " is not same as " + s2.ToString());
        }

        if (s1 != s2)
        {
            Console.WriteLine(s1.ToString() + " is not same as " + s2.ToString());
        }
    }
}


Downloads

The sample code can be downloaded from below link. The code is complied with Microsoft Visual C# 2005.




Copyright © 2008 www.codematrix.net, All Rights Reserved. Disclaimer