locked
How to convert dynamic boolean null value to false RRS feed

  • Question

  • User-1262787652 posted

    I'm creating ASP.NET MVC4 C# application which accepts dynamic queries and generates razor views dynamically.

    Application uses WebMatrix.Data.Query() to get data. This method returns IEnumerable<dynamic> .

    Result rows can contain bool? type properties whise value is null.

    Those values are used in dynamically generated razor views with && , || and ! operators. Those operatos does not accept null boolean values, runtime exception occurs in this case.

    I'm looking for a way to fix this. It seems that best way is to convert dynamic boolean null values to false.

    I tried  method

            public static dynamic BooleanNullToFalse(dynamic value)
            {
                if (value == null && value is bool?)
                    return false;
                return value;
            }

    but got strange compile error

     One or more types required to compile a dynamic expression cannot be > found. Are you missing a reference?

    in expression `value == null`

    How to fix this so that code compiles ?

    Another possibility would be to force &&, || and ! to accept boolear null values or define new boolean operators which accept null

    values but I dont know is this possible.

    Tuesday, May 13, 2014 3:22 PM

Answers

  • User281315223 posted

    Have you considered using the Convert.ToBoolean() method? It will return false if your object is null, otherwise it will return the appropriate value :

    public static bool BooleanNullToFalse(dynamic value)
    {
        return Convert.ToBoolean(value);
    }

    Mike's approach should work as well without any issues.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 13, 2014 4:38 PM

All replies

  • User-821857111 posted

    Try this:

    public static bool BooleanNullToFalse(dynamic value)
    {
        return value == null ? false : value;
    }

    Tuesday, May 13, 2014 4:34 PM
  • User281315223 posted

    Have you considered using the Convert.ToBoolean() method? It will return false if your object is null, otherwise it will return the appropriate value :

    public static bool BooleanNullToFalse(dynamic value)
    {
        return Convert.ToBoolean(value);
    }

    Mike's approach should work as well without any issues.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 13, 2014 4:38 PM