Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 645
Max Yankov Avatar asked Oct 31 '12 12:10

Max Yankov


People also ask

What is overloading in C with example?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java.

What is meant by overloading operator?

Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.

What is operator overloading and its types?

Operator Overloading is the method by which we can change the function of some specific operators to do some different task. In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded.

Can we overload () operator?

The function call operator () can be overloaded for objects of class type. When you overload ( ), you are not creating a new way to call a function. Rather, you are creating an operator function that can be passed an arbitrary number of parameters.


1 Answers

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;
like image 185
fero Avatar answered Oct 04 '22 04:10

fero