Thursday 2 January 2014

Operator Overloading in C#

In this article we are going to see the operator overloading , operator overloading is a concept where we can overload the method using the Operator , in which the operation between the interaction objects can be defined based on symbol.Let we see  a sample scenario where we can see the stringoperation is a class which have the MethodName is string, when two objects are interact with summation operator then the
result will be the concat of the MethodName with intermediate , symbol

C#


    class Program
    {
        static void Main(string[] args)
        {
            StringOperation operation1 = new StringOperation() { MethodName="public"};
            StringOperation operation2 = new StringOperation() { MethodName = "private" };
            StringOperation operation3 = operation1 + operation2;
            Console.WriteLine(operation3.ToString());
            Console.Read();
        }
    }

    class StringOperation
    {
        public string MethodName { set; get; }

        public static StringOperation operator + (StringOperation operation1, StringOperation operation2)
        {
            return new StringOperation() {MethodName = operation1.MethodName+","+operation2.MethodName };
        }

        public override string ToString()
        {
            return MethodName;
        }
    }




Output:
public,private

From this article you can see how to implement the Operator overloading.

No comments:

Post a Comment