Question

I'm trying to implement an IValueConverter which takes a nullable type e.g. int? Enum? etc. and returns a bool (true if it has a value, false otherwise). I don't know the type of nullable beforehand.

The boxed value (of type object) does not have a .HasValue and I don't know for sure that a simple (value == null) will not reflect the nullness of passed object or if anything was passed to the method or not. Moreover it is not possible to cast value as a Nullable and tehre does not seem to be an INullable interface I can use.

Basically, do I need to cast in order to determine the nullness of a boxed object?

Here is what I have ...

public class NullableHasValueToBool : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        // Unsure if this is really the nullness of the passed object
        return (value != null);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        throw new NotImplementedException();
    }
}
Was it helpful?

Solution

I don't know for sure that a simple (value == null) will not reflect the nullness of passed object

It will.

or if anything was passed to the method or not

Passing a nullable with HasValue to False or passing no value to a method are basically the same thing.

private static void Test()
{
    System.Diagnostics.Debug.WriteLine(IsNull(new int?())); // Displays True
}

private static bool IsNull(object obj)
{
    return obj == null;
}

OTHER TIPS

This is what I use.

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool param = bool.Parse(parameter.ToString());
        if (value == null)
        {
            return false;
        }
        else
        {
            return !((bool)value ^ param);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool param = bool.Parse(parameter.ToString());
        return !((bool)value ^ param);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top