Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 8
    Also - if you're unsure if v1 contains null - you can use the null-coalescing operator to set a fallback value. E.g. v2 = v1 ?? 0; Commented May 13, 2011 at 17:02
  • 16
    And be sure to check v1.HasValue first. Commented May 13, 2011 at 17:02
  • 4
    MSDN says, that this will throw an exception if the v1 is null. In my opinion, this is not a correct answer. Commented Oct 24, 2015 at 21:41
  • 10
    @ventiseis I would think that's desirable behavior -- I'm surprised so many of the other answers are ok with silently converting a null to 0. If you're assigning a nullable type to a non-nullable type, you should be sure that the value isn't actually null. OP didn't say "I want to assign v1 to v2, or 0 if v1 is null", but that's what everyone seemed to assume Commented Mar 15, 2016 at 6:39
  • I don't remember which version of c# got the ! operator (null forgiveness) but due to business logic i KNOW the int? is not null. I use v2 = v1!.Value to get my value. And as @MichaelMrozek pointed out, I DO want an exception thrown, because somewhere my business got messed up. FYI I need a non null int so I can pass it to another function. Commented Nov 10, 2023 at 21:38