Follow

# popolo - code simple..

Follow # C#: complex numbers p1: defining the class

Dimitris Mageiras
·Apr 17, 2022·

Let's see a simple way to model complex numbers in C#.

First of all, let's create a simple console project in .NET Core and add a class file into the solution. We choose Z as the name of the class to match the mathematical notation of complex numbers:

``````class Z
{
public double x;
public double y;
}
``````

We've added two variables, x and y of type double.

To express z = 5 + 10i we will have to type:

``````z = new Z() { x = 5, y = 10 };
``````

It would be handier if we could type:

``````var z = new Z(5,10);
``````

So let's provide a constructor to Z class:

``````public Z(double x, double y)
{
this.x = x; this.y = y;
}
``````

Now we can use the shorter (and handier) form:

``````var z = new Z(-1 , 2);
``````

What if we wanted to present the complex number in a mathematical way?

Let's override ToString() method.

``````public override string ToString()
{
string sign = y >= 0 ? "+" : "";
return \$"{x}{sign}{y}i";
}
``````

Now, this is possible:

``````Console.WriteLine(new Z(-5, -4));
``````

The ouput will be:

``````-5-4i
``````