GetValueOrDefault

Here’s another method that comes under the category, “Methods that I wish I’d have found at least six months ago”.

Nullable objects all implement an overloaded method called GetValueOrDefault, which – as the name suggests – returns the value of the nullable object if it has been assigned one (i.e. HasValue returns true), or a default value (being either the default value for the type, or a default value that you provide). So, instead of writing code like this (note: I’d never really write this method, but it serves as an example):


public int GetValueOfNullableInt(int? nullableInt) {
    return nullableInt.HasValue ? nullableInt.Value : default(int);
}

You can instead use this (and again, pointless code used as an example only):


public int GetValueOfNullableInt(int? nullableInt) {
    return nullableInt.GetValueOrDefault();
}

The overloaded method lets you pass in a default value you wish to have returned should the nullable not have a value. Is nice!

Posted in .Net, C# by Gerrod at July 16th, 2007.

4 Responses to “GetValueOrDefault”

  1. Henrik says:

    // my method body
    int newInt = someNullableInt ?? default(int);
    // more of my method body.

    —-

    Let’s not complicate things.

  2. gerrod says:

    True – the null coalescing operator can be used for this purpose as well.

    Still, I think “GetValueOrDefault” is more readable, which is always a good thing.

  3. Ben says:

    I don’t think Gerrod is advocating the use of creating a method just to wrap the GetValueOrDefault call (as stated by the comment – pointless code is an example only).

    Therefore I think

    return nullableInt.GetValueOrDefault();
    and

    return nullableInt ?? default(int);

    are both just as readable as the other, with the exception that some n00bs might not understand the coalescing (??) operator.

  4. Henrik says:

    “advocating the use of creating a method just to wrap” — aha, well then, I agree with you ^^

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Quickduck logo