Why static implicit operator doesn't work on DynamicObject inherited classes ? And how to fix it?

StackOverflow https://stackoverflow.com/questions/21407270

Question

Code :

public class t : System.Dynamic.DynamicObject
{

    public dynamic Value;

    public static implicit operator t(int value)
    {
        if (value > 100) value = 100;
        t x = new t();
        x.Value = value;
        return x;
    }
}

Usage :

dynamic f = new t();
f = 44; // the implicit operator doesn't get called

However if I change implicit to explicit and use it like f = (int)44) the explicit operator is called.

EDIT: I want my class to inherit from DynamicObject.

How to fix this issue ?

Was it helpful?

Solution

You use:

dynamic f = new t();  // f has type 'dynamic', no compile-time link between f and type 't'
f = 44; // the implicit operator doesn't get called

Why would assigning 44 to a variable of type dynamic convert that 44 through any user-defined operator? It simply puts 44 (or rather a boxed 44) into f.

Compare with:

t f = new t();
f = 44;

OTHER TIPS

When you set f = 44;, it is not changing the value of the object. Rather, it is reassigning the f variable to point to a new object. By default, the new object will be an int, since it's an int literal. If you want to create a new t object that equals 44, you need to cast it to that type, like this:

f = (t)44;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top