Gotchas when making use of Nullable<T> in C# 4 -


I have just started writing on the component where I found out that it would be useful to tap some properties instead While letting them support the default value, I realized that I have ever used the non-null-type of syntax or faucet & lt; T & gt; Never before typing, jumping out soon and cutting me Nullable & lt; T & gt; and short story ?

  • How do I work around them?

  • When I start, what are the biggest advantages / new possibilities available to me by using them?

  • Attempt to assign a normal hold to an empty space The variable with a conditional expression is as follows:

      bool useDefault = true; Int defaultValue = 50; Int? Y = use default? Default Price: Zero;  

    At first glance it may appear that this should work, but in reality it returns a compilation error:

     The type of conditional expression can not be determined because There is no underlying conversion in 'int' and 'end lieutenant; Tull> '

    Solution: Add an artist to one or both of the possible outcomes:

      int? Y = use default? DefaultValue: (int?) Faucet; It is generally safe to assume that the integer  a & lt; = 5  and ! (A & gt; 5)  are not equal to this assumption is not correct for an empty integer. 

      int? X = Null; Console.light line (xlt; = 5); Console.light line (! (X> 5));  

    Result:

     wrong truth 

    Solution: Handle a separate null case.


    Here is another case: the above change:

      int? Y = null; Int? Z = Null; Console The white line (y == z); Console Writer (y & lt; = z);  

    Output:

     True False 

    then y is equal to Z , but it is not less or equal to z .

    Solution: Again, treating the tap case separately can be astonished.


    Comments