Max Yankov
Max Yankov

Reputation: 13297

Overloading = operator in C#

OK, I know that it's impossible, but it was the best way to formulate the title of the question. The problem is, I'm trying to use my own custom class instead of float (for deterministic simulation) and I want to the syntax to be as close as possible. So, I certainly want to be able to write something like

FixedPoint myNumber = 0.5f;

Is it possible?

Upvotes: 17

Views: 1895

Answers (4)

cuongle
cuongle

Reputation: 75306

Overload implicit cast operator:

class FixedPoint
{
    private readonly float _floatField;

    public FixedPoint(float field)
    {
        _floatField = field;
    }

    public static implicit operator FixedPoint(float f)
    {
        return new FixedPoint(f);
    }

    public static implicit  operator float(FixedPoint fp)
    {
        return fp._floatField;
    }
}

So you can use:

FixedPoint fp = 1;
float f = fp;

Upvotes: 8

ΩmegaMan
ΩmegaMan

Reputation: 31596

If the Implicit is not what you want in = overloading, the other option is to use the explicit operator on your class such as below, which one will cast to it, making it understood by the user:

public static explicit operator FixedPoint(float oc)     
{         

     FixedPoint etc = new FixedPoint();          
     etc._myValue = oc;          
     return etc;      
}

... usage

FixedPoint myNumber = (FixedPoint)0.5f;

Upvotes: 1

Vishal Suthar
Vishal Suthar

Reputation: 17193

Create an implicit type cast.

This is an example:

<class> instance = new <class>();

float f = instance; // We want to cast instance to float.

public static implicit operator <Predefined Data type> (<Class> instance)
{
    //implicit cast logic
    return <Predefined Data type>;
}

Upvotes: 1

fero
fero

Reputation: 6183

Yes, by creating an implicit type cast operator for FixedPoint if this class was written by you.

class FixedPoint
{
    public static implicit operator FixedPoint(double d)
    {
        return new FixedPoint(d);
    }
}

If it's not obvious to the reader/coder that a double can be converted to FixedPoint, you may also use an explicit type cast instead. You then have to write:

FixedPoint fp = (FixedPoint) 3.5;

Upvotes: 33

Related Questions