I’ll start this post with an example:
public class MyClass
private int m_HeldInteger = 0;
public static implicit operator int(MyClass myClass)
public static void Main(string args)
MyClass c = new MyClass();
bool b = c is int;
What have we here? We have the type MyClass which holds an integer field and has an implicit conversion to an integer.
Now let’s look at the Main method. In it, we instantiate the variable c to be of type MyClass. We then inquire the runtime to whether c is of type int or any of its descendants.
It’s pretty obvious that the answer will be no, so we will get a false assigned to the boolean variable b.
What I find wrong with this is that, effectively, c could indeed be of type int, because we can implicitly convert it to that type.
In this particular case, the compiler chooses to not translate our object to int prior to the execution of this expression, causing it to always return false. Was I to explicitly cast c into int, no exception would be thrown (since a call would be made to the implicit operator) and the value returned would be true.
This is correct behavior because, yes, the object c is indeed not of type int. On the other hand, this is not correct beahvior, since it could be of type int.
What do you think? Should this stay like it is or should it be changed?