?? operator

I just discovered a new Operator in .Net 2.0…

the ?? operator.

One of the most anoing things to do when retrieving data, is checking for null values:

string myValue = dataReader.IsDBNull(2) ? string.Empty : dataReader.GetString(2);

But the ?? operator makes it a lot easier:

string myValue = dataReader.GetString(2)??string.Empty;

Why didn’t anybody tell me about this before?????

Read more here : http://msdn2.microsoft.com/en-us/library/ms173224(VS.80).aspx

Comments

3 responses to “?? operator”

  1. Henrik Avatar

    Unfortuanly it doesn’t work on valuetypes.
    So reader.GetInt(x) ?? wouldn’t work.

    Do you have an idea what to do?

  2. priisholm Avatar

    Seems to do quite the job as the || “double pipe” operator does in JavaScript and Ruby, and the ‘or’ operator in Python

    //JavaScript:
    var myVar = obj.returnNullValue() || “”;

    #Ruby
    my_var = obj.return_nil_value || “”

    #Python
    myvar = obj.return_none_value() or ”

    Ruby even has several conditional assignment operators, f.ex. as shown in this function

    def user_name
      @user_name ||= “Anonymous Coward”
    end

    This either returns the name stored in the @user_name instance variable or , if it is null, assigns the name “Anonumous Coward” to the variable and returns it. Neat, huh? ๐Ÿ™‚

    Yeah, yeah, I know; these are all dynamic scripting languages, but it’s interesting to see how many of the dynamic language paradigms sneak into the static languages these days.

    Cheers,
    Kenneth

  3. stuz Avatar

    @priisholm: Hvordan faar du null coalescing til at vaere dynamic language baseret? ๐Ÿ˜‰

    At det samme ka la sig goere med en OR operator i perl, python, ruby, et. er en del af hvordan vaerdier og null-vaerdier blir haandeteret i nontype staerke entiteter i forskellige sprog ๐Ÿ˜‰

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.