Overload an Operator in C# 4.0

Its very easy to overload operators in C# 4.0.

You can add different overloading values such as +,-,* or /

But we will be focusing on "+" in this blog. 

Lets say we create a class named Word:


public class Word
    {

        public string Text
        {
            get;
            set;
        }

        public static string operator +(Word w1, Word w2)
        {
            return w1.Text + " " + w2.Text;
        }

        public static Word operator +(Word w, int j)
        {

            return new Word()
            {
                Text=w.Text + j.ToString()
            };
        }

        public override string ToString()
        {
            return Text;
        }


    }
    class Program
    {
        static void Main(string[] args)
        {

            Word word1 = new Word() { Text = "Hello" };
            Word word2 = new Word() { Text = "World" };

            Console.WriteLine(word1);
            Console.WriteLine(word2);
            Console.WriteLine(word1 + word2);
            Console.WriteLine(word1 + 7);

            Console.ReadLine();
        }
    }



As you can see its very easy to overload an operator.You can add these (+,-,*,/) values after operator keyword.

And im fully surprised how fast C# 4.0 compiler is! Its like as if im building an application in C++


Dont you think?
Next Recommended Reading How to use Tuple in c# 4.0