views:

91

answers:

3
+3  Q: 

Checking for nulls

Sorry for such simple question.

How would I check this for nulls?

obj.DivisionNotes = (string)row["DivisionNotes"];

I'm thinking something like this.

obj.DivisionNotes = (string)row["DivisionNotes"]?null:"No notes";

Am I right.

Any help much appreciated.

+10  A: 

Your casting of a null will cause a problem, you can use an as cast along with the null coalescing operator to solve your issues..

obj.DivisionNotes = (row["DivisionNotes"] as string) ?? "No notes";
Quintin Robinson
Thanks, I appreciate your help.
Chin
No problem, Glad it worked out for you.
Quintin Robinson
+1  A: 

You could use the ISNULL function in your original T-SQL query, changing a query like this:

SELECT ID, Name, DivisionNotes FROM tblWHATEVER

to

SELECT ID, Name, ISNULL(DivisionNotes, 'No notes') AS 
    DivisionNotes FROM tblWHATEVER

I'm not saying this is better than checking for null in your code, but sometimes a simple change in your query can save you from changing your code in a bunch of different places.

MusiGenesis
Interesting, I wonder why you got a minus vote for that idea. Anyway thanks for the input.
Chin
@Chin: someone figured I didn't really answer your question.
MusiGenesis
+1  A: 

There are many way to handle nulls in a datarow. Please this other post where I explain multiple method of doing that.

Pierre-Alain Vigeant