Flxb
Flxb

Reputation: 63

Implicit type conversion of anonymous object

I try to convert to float anonymous object of class that have float implicit converter. I'm not sure if I explain it correctly. Here is example:

I have following class:

public class MyFloat 
{        
    public float Value { get; set; }

    public MyFloat(float val)
    {
        Value = val;
    }

    public static implicit operator MyFloat(float v) 
    {
        return new MyFloat(v);
    }

    public static implicit operator float(MyFloat d) 
    {
        return d.Value;
    }

Then if I try to:

object f1 = new MyFloat(5.0f);
float f2 = f1; // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
float f3 = (MyFloat)f1; 

I get InvalidCastException. I assume that f1 is treated as object and it's not checked if it's real type (MyFloat) have implicit to float converter. Is there any way to workaround this problem?

Thanks in advance

Upvotes: 0

Views: 244

Answers (2)

James
James

Reputation: 82136

The problem here is, like you say, f1 is treated as object, not MyFloat - you need to cast it from object back to MyFloat and then the implicit cast will work (like your second example).

Alternatively, don't declare it as object to start with and use it's real type - MyFloat.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460288

Don't use object but MyFloat, otherwise the compiler does not know at compile time that your object is of type MyFloat:

Instead of:

object f1 = new MyFloat(5.0f);
float f2 = f1; // Unhandled Exception: System.InvalidCastException: Specified cast is not 

this:

MyFloat f1 = new MyFloat(5.0f);
float f2 = f1;  

or cast it accordingly (although that seems to be redundant):

float f2 = (MyFloat)f1

Upvotes: 1

Related Questions