Translate

Sunday, October 13, 2013

C# operator overloading and conversion operator example

Operator overloading means you can give your own meaning to an operator (+,- etc) when working on specific types. In the example below I will make it possible to add two complex numbers.


using System;
using System.Collections.Generic;
using System.Threading;



internal class Playground
{
   
    private static void Main(string[] args)
    {
        var c1 = new ComplexNumber {Real = 1,Imaginary =2};
        var c2 = new ComplexNumber { Real = 2, Imaginary = 2 };
        var c3 = c1 + c2;
    }

    public struct ComplexNumber
    {
        public int Real { get; set; }
        public int Imaginary { get; set; }

        public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
        {
            var result = new ComplexNumber {Real = (c1.Real + c2.Real), Imaginary = (c1.Imaginary + c2.Imaginary)};
            return result;
        }
    }

  
}

I could also provide a method to convert an integer to a complex number, using a converter operator as shown below.


using System;
using System.Collections.Generic;
using System.Threading;



internal class Playground
{
   
    private static void Main(string[] args)
    {
        var c1 = new ComplexNumber {Real = 1,Imaginary =2};
        var c2 = new ComplexNumber { Real = 2, Imaginary = 2 };
        var c3 = c1 + c2;

        var c4 = (ComplexNumber) 5;//Convert an int into a complex number
    }

    public struct ComplexNumber
    {
        public int Real { get; set; }
        public int Imaginary { get; set; }

        public static implicit operator ComplexNumber(int i)
        {
            return new ComplexNumber {Real = i};
        }

        public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
        {
            var result = new ComplexNumber {Real = (c1.Real + c2.Real), Imaginary = (c1.Imaginary + c2.Imaginary)};
            return result;
        }
    }

  
}




No comments:

Post a Comment

Comments will appear once they have been approved by the moderator