Tuesday, 27 March 2018

C # tutorial Operator Overloading

Operator Overloading
C# oprator have some special meaning ,but you can change and redefine operator meaning.

Some Point to remember before define Operator Overloading
  • The method should be a public and static method
  • The method is marked by keyword "operator" followed by the operator symbol

Below is the example of of unary(+) operator overloading

 
Example 1

using System;
public class Program
{
                  public static void Main()
                  {

                         Area obj1 = new Area(10,10);
                         Area obj2= new Area(15, 12);

                         Area overlod_obj = obj1 + obj2;

                         Console.WriteLine("Value of mX :"+overlod_obj.GetValX().ToString());
                         Console.WriteLine("Value of mY :" + overlod_obj.GetValY().ToString());

                         Console.ReadKey();
                  }
}


class Area
{
            int mX;
            int mY;

            public Area(int x, int y)
            {
                mX = x;
                mY = y;
            }

            public static Area operator +(Area m1, Area m2)
            {
                return new Area(m1.mX * m2.mX, m2.mY * m2.mY);
            }

           public int GetValX()
          {
              return mX;
          }

          public int GetValY()
         {
            return mY;
         }

}

Output :
Value of mX :150
Value of mY :144


Below is the table , showing  Operator,Operator Type and Overloading Possible or not

Operator Type Operator Overloading Possible
unary +, -, !, ~, ++, -- Yes
binary +, -, *, /, % Yes
comparison ==, !=, <, >, <=, >= Yes
conditional &&, || Yes
assignment +=, -=, *=, /=, %= No
Misc.. =, ., ?:, ->, new, is, sizeof, typeof No




Below is the example of of unary(++) operator overloading


Example 2

using System;

public class Program
{
           public static void Main()
           {
     
                 Area obj1 = new Area(10);

                Console.WriteLine("Value of m :" + obj1.GetValueX().ToString());

                Area obj2 = obj1++;

                Console.WriteLine("Value of m :" + obj2.GetValueX().ToString());

               Console.ReadKey();
          }
}


class Area
{

         int m;

        public Area(int x)
         {
             m = x;
        }

         public static Area operator ++(Area obj)
        {
             obj.m++;
             return obj;
        }

        public int GetValueX()
        {
              return m;
        }
}

Output :
Value of m :10
Value of m :11


No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...