I have a custom class, ComplexNumber
, which is as you may expect a way to represent complex numbers:
class ComplexNumber
{
double realPart;
double imaginaryPart;
public ComplexNumber(double real, double imaginary)
{
realPart = real;
imaginaryPart = imaginary;
}
}
The context of this question is that if you want to set default C# classes such as a double or a float to a certain value which is an integer, you can write
float f = 2;
I want to be able to write something similar like
ComplexNumber c = 2;
which will create a new variable of the ComplexNumber
class with its realPart
set to 2
and its imaginaryPart
set to 0
. To write ComplexNumber c = new ComplexNumber(2, 0)
is much more tedious, and I am wondering if there is a way to create these instances of a custom class more implicitly like how the default C# classes behave.
You can add an implicit (or expicit) operator to your class like so:
public static implicit operator ComplexNumber(int i) => new ComplexNumber(i, 0);
That will allow you do what you want.
As you used 2
as a literal, that will be an int
in C#, this then relies on the fact that int
is implicitly convertable to double
in the contructor call to ComplexNumber
.