1

I created an IValueConverter that converts a bool to a System.Windows.Visibility object (it does the opposite of BooleanToVisibilityConverter). It works fine, except when I try to use it on an Observable<bool> object. Observable<T> is a class I defined with an implicit operator to convert it to a T. The problem is that when unboxing it as a bool, I get an InvalidCastException.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if ((bool)value) // InvalidCastException
    {
        return Visibility.Hidden;
    }
    else
    {
        return Visibility.Visible;
    }
}

It seems that C# is ignoring my implicit operator when the Observable is boxed as an Object. For example:

Observable<bool> obs = new SimpleObservable<bool>(true);
object obj = obs;

// This conversion works just fine:
bool bval = (bool)(Observable<bool>)obj;

// This conversion throws an InvalidCastException:
bval = (bool)obj;

Is there any way to guarantee that my Observable<bool> can be unboxed as a bool?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
hypehuman
  • 1,290
  • 2
  • 18
  • 37

1 Answers1

3

Is there any way to guarantee that my Observable can be unboxed as a bool?

No. This code is reminiscent of Nullable, and that took direct support from the compiler to accomplish the task.

The issue is that implicit doesn't create a true implicit conversion, at runtime. It's purely compile time syntactic sugar. Any time the compiler notices that you're trying to put an expression of type X into a variable that expects type Y it looks in the definition of X and Y, at compile time, for an implicit conversion operator and, if found, puts the appropriate static method call in place to do the conversion. By the time you get to runtime there is no knowledge left of any implicit (or explicit) conversion operators. All that's left are the few that are baked into the language, such as between primitive types and between types in a type hierarchy.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • 2
    I vote that "Compile time syntactic sugar" should become a permanent techinal phrase because of its awesomeness. – Colin Pear Jan 14 '13 at 22:34