nullable types

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tony

    #1

    nullable types

    Hello!

    This construction
    int? op1 = 5;
    int result = op1 * 2;

    gived a compile error with
    Error 1 Cannot implicitly convert type 'int?' to 'int'. An explicit
    conversion exists (are you missing a cast?)
    C:\tony\Console Application1\Co nsoleApplicatio n1\Program.cs 12 26
    ConsoleApplicat ion1

    If I instead have this construction
    int? op1 = 5;
    int result = op1 * 2 ?? 12;
    Then no compile error will occur.

    I mean that because I don't have a nullable type for result it should
    give a compile error as the first example did.

    //Tony


  • Jon Skeet [C# MVP]

    #2
    Re: nullable types

    On Jun 30, 10:18 am, "Tony" <johansson.ande rs...@telia.com wrote:
    This construction
    int? op1 = 5;
    int result = op1 * 2;
    >
    gived a compile error with
    Error 1 Cannot implicitly convert type 'int?' to 'int'. An explicit
    conversion exists (are you missing a cast?)
    C:\tony\Console Application1\Co nsoleApplicatio n1\Program.cs 12 26
    ConsoleApplicat ion1
    >
    If I instead have this construction
    int? op1 = 5;
    int result = op1 * 2 ?? 12;
    Then no compile error will occur.
    >
    I mean that because I don't have a nullable type for result it should
    give a compile error as the first example did.
    No, the result is a non-nullable type.

    An expression of the form "a ?? b" is of the same type as b - if
    that's nullable, the result will be nullable. If it's non-nullable,
    the result will be non-nullable.
    (This is glossing over a lot of potential conversions between the
    types of a and b, but it's the basic idea.)

    The only way that you can get a null value from a ?? b is if b is
    null, which it can't be if the type of b is non-nullable.

    Jon

    Comment

    Working...