Is there any difference between type? and Nullable?

前端 未结 9 1137
礼貌的吻别
礼貌的吻别 2020-12-15 15:53

In C# are the nullable primitive types (i.e. bool?) just aliases for their corresponding Nullable type or is there a difference between th

相关标签:
9条回答
  • 2020-12-15 16:13

    To access the value of the bool? you need to do the following:

    bool? myValue = true;
    bool hasValue = false;
    
    if (myValue.HasValue && myValue.Value)
    {
      hasValue = true;
    }
    

    Note you can't just do:

    if (myValue)
    {
      hasValue = true;
    }
    
    0 讨论(0)
  • 2020-12-15 16:18

    A bool is a value type, therefore it can't contain a NULL value. If you wrap any value type with Nullable<>, it will give it that ability. Moreover, access methods to the value change by additional properties HasValue and Value.

    But to the question: Nullable<bool> and bool? are aliases.

    0 讨论(0)
  • 2020-12-15 16:18

    No there is no difference. In summary:

    System.Boolean -> valid values : true, false

    bool -> alias for System.Boolean

    Nullable<bool> -> valid values : true, false, null

    bool? -> alias for Nullable<bool>

    Hope this helps.

    0 讨论(0)
  • 2020-12-15 16:23

    I'm surprised nobody went to the source (the C# spec) yet. From §4.1.10 Nullable types:

    A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable<T>, and the two forms can be used interchangeably.

    So, no, there isn't any difference between the two forms. (Assuming you don't have any other type called Nullable<T> in any of the namespaces you use.)

    0 讨论(0)
  • 2020-12-15 16:24

    There is no difference between bool? b = null and Nullable<bool> b = null. The ? is just C# compiler syntax sugar.

    0 讨论(0)
  • 2020-12-15 16:26

    A Nullable<T> is a structure consisting of a T and a bit flag indicating whether or not the T is valid. A Nullable<bool> has three possible values: true, false and null.

    Edit: Ah, I missed the fact that the question mark after "bool" was actually part of the type name and not an indicator that you were asking a question :). The answer to your question, then, is "yes, the C# bool? is just an alias for Nullable<bool>".

    0 讨论(0)
提交回复
热议问题