Value type that overloads operators for adding, subtracting and multiplying complex numbers. - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Value type that overloads operators for adding, subtracting and multiplying complex numbers.

Demo Code



using System;//from ww w.  j av a2s .  co m

public struct ComplexNumber
{
   public double Real { get; }
   public double Imaginary { get; }

   public ComplexNumber(double real, double imaginary)
   {
      Real = real;
      Imaginary = imaginary;
   }

   public override string ToString() => $"({Real} {(Imaginary < 0 ? "-" : "+")} {Math.Abs(Imaginary)}i)";

   public static ComplexNumber operator+(ComplexNumber x, ComplexNumber y)
   {
      return new ComplexNumber(x.Real + y.Real, x.Imaginary + y.Imaginary);
   }

   // overload the subtraction operator
   public static ComplexNumber operator-(ComplexNumber x, ComplexNumber y)
   {
      return new ComplexNumber(x.Real - y.Real, x.Imaginary - y.Imaginary);
   }

   // overload the multiplication operator
   public static ComplexNumber operator*(ComplexNumber x, ComplexNumber y)
   {
      return new ComplexNumber(
         x.Real * y.Real - x.Imaginary * y.Imaginary,
         x.Real * y.Imaginary + y.Real * x.Imaginary);
   }
}


class MainClass
{
   static void Main()
   {
      Console.Write("Enter the real part of complex number x: ");
      double realPart = double.Parse(Console.ReadLine());
      Console.Write("Enter the imaginary part of complex number x: ");
      double imaginaryPart = double.Parse(Console.ReadLine());
      var x = new ComplexNumber(realPart, imaginaryPart);

      // prompt the user to enter the second complex number
      Console.Write("\nEnter the real part of complex number y: ");
      realPart = double.Parse(Console.ReadLine());
      Console.Write("Enter the imaginary part of complex number y: ");
      imaginaryPart = double.Parse(Console.ReadLine());
      var y = new ComplexNumber(realPart, imaginaryPart);

      // display the results of calculations with x and y
      Console.WriteLine();
      Console.WriteLine($"{x} + {y} = {x + y}");
      Console.WriteLine($"{x} - {y} = {x - y}");
      Console.WriteLine($"{x} * {y} = {x * y}");
   }
}

Result


Related Tutorials