6 Mart 2018

C# Operator Overloading

 
using System;

namespace OperatorOverloadingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Complex(3, 4);
            var b = new Complex(3, -4);
            Console.WriteLine($"a = {a}");
            Console.WriteLine($"b = {b}");
            Console.WriteLine($"-b = {-b}");
            Console.WriteLine($"a+b = {a + b}");
            Console.WriteLine($"a-b = {a - b}");
            Console.WriteLine($"a*b = {a * b}");
            Console.WriteLine($"a == b = {a == b}");
            Console.WriteLine($"a != b = {a == b}");
            Console.WriteLine($"++b = {++b}");
            Console.WriteLine($"a*b = {a * b}");
            /*ÇIKTI:
            a = 3 + 4i
            b = 3 - 4i
            -b = -3 + 4i
            a+b = 6 + 0i
            a-b = 0 + 8i
            a*b = 25 + 0i
            a == b = False
            a != b = False
            ++b = 4 - 3i
            a*b = 24 + 7i
            */

        }

        //struct yerine class da kullanılabilir.
        public struct Complex
        {
            private int r;

            //imagine number
            private int i;


            public int R => r;
            //imagine number
            public int I => i;


            public Complex(int r, int i)
            {
                this.r = r;
                this.i = i;
            }
            public Complex(int r)
            {
                this.r = r;
                this.i = 0;
            }

            public override string ToString()
            {
                if (I < 0)
                    return $"{R} - {-1 * I}i";
                else return $"{R} + {I}i";
            }


            //Overload Methods
            // Unary Operators +, -, !, ~, ++, --

            // -
            public static Complex operator -(Complex x) => new Complex(-x.R, -x.I);

            //++
            public static Complex operator ++(Complex x) => new Complex(x.R + 1, x.I + 1);

            //--
            public static Complex operator --(Complex x) => new Complex(x.R - 1, x.I - 1);


            //Binary operators +, -, *, /, %

            // + 
            public static Complex operator +(Complex x, Complex y) => new Complex(x.R + y.R, x.I + y.I);

            // - : burada - unary ve + işlemini birlikte kullandık
            public static Complex operator -(Complex x, Complex y) => x + (-y);

            //*
            public static Complex operator *(Complex x, Complex y)
            {
                return new Complex(x.R * y.R - x.I * y.I, x.R * y.I + x.I * y.R);
            }


            //Comparison Operators ==, !=, <, >, <=, >=
            public static bool operator ==(Complex x, Complex y) => x.R == y.R && x.I == y.I;

            public static bool operator !=(Complex x, Complex y) => !(x == y);


        }
    }
}

 
Kaynak: https://www.tutorialspoint.com/csharp/csharp_operator_overloading.htm