CodeThings

Things i discover during my everyday life of trying build some decent code.

I have my own consulting company, Eqa, in which a assist companies in developing web applications based on various microsoft.net technologies.

Monday, September 24, 2007

?? 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

4 comments:

Henrik said...

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

Do you have an idea what to do?

priisholm said...

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

stuz said...

@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 ;)

stuz said...

@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 ;)