Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning a value to an instance of a class in C# implicitly

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading