3

I am returning a scalar value from a SQL Server 2008 database:

string reason = cmd.ExecuteScalar().ToString() ?? : "";

I want to make sure that if null is returned, that reason = "" and not null.

i am getting an error on this line:

Error 3 Invalid expression term ':'

How can this be fixed?

EDIT:

thank you for the changes on the colon, now i am getting this exception on the same line:

string reason = cmd.ExecuteScalar().ToString() ?? "";
System.NullReferenceException occurred
  Message="Object reference not set to an instance of an object."
Adam Miller
  • 767
  • 1
  • 9
  • 22
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • 1
    If the result is NULL it will still cause an exception so the simple solution is to make sure the value within the database cannot be NULL. An alternative simple solution is make sure the value stored in the database is set to the String type which means IF its null it won't cause an exception. in C# a String that has no value is an empty string. A string variable default value is null and if displayed say on a console window would be an empty string or null character ( so nothing would be printed ). – Security Hound Jul 15 '11 at 17:22
  • See my answer below (particularly the last part). – canon Jul 15 '11 at 17:38
  • If you're getting a `NullReferenceException` now, it would indicate that `cmd` is `null`. – Jacob Jul 15 '11 at 20:23

7 Answers7

10

Try this:

string reason = cmd.ExecuteScalar().ToString() ?? "";

BUT: this will still fail, since if .ExecuteScalar() returns a NULL, you're already causing a Null Reference Exception by calling .ToString() on that NULL value......

So I guess the ?? operator really doesn't help you here... do the "usual" dance:

object result = cmd.ExecuteScalar();

if(result != null)
{  
   reason = result.ToString();
}
else
{
   reason = "(NULL value returned)";
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Would `string reason = (cmd.ExecuteScalar() ?? String.Empty).ToString();` work? Anyways, +1 for having the only right answer... (or at least until 1 minute ago...) – Ry- Jul 15 '11 at 17:21
  • Had the same - doesn't make sense. The original question was explained by removing the ':', so OP was then edited making most of those answers invalid - case of moving goalposts. I just deleted my answer and whoever's down-voting can take a run and jump! – cristobalito Jul 15 '11 at 17:24
  • @marc, you correctly point out a flaw, you correctly point out ?? alone does not solve the problem. However, it is mistaken to say you have "*the* right answer," because you've provided no solution! Do you disagree? – Anthony Pegram Jul 15 '11 at 17:24
  • @marc_s: I have no idea. Competitive answerers? :P Why is yours appearing 3rd in the list when it has more upvotes than the rest, is what I'm wondering... – Ry- Jul 15 '11 at 17:26
  • @Anthony Pegram: the "solution" (just explicitly check for `!= null` on the return value from `ExecuteScalar`) seemed so overly obvious, that I didn't bother adding it before...... – marc_s Jul 15 '11 at 17:27
  • @marc_s: The original question was overly obvious.. a quick search for the ?? operator would have solved the initial syntax problem, but you bothered to answer that? – Coeffect Jul 15 '11 at 17:29
  • @marc, with all of the questions titled "object reference not set to instance of object," we really ought not to assume! Indeed, the asker edited the same exception into the question. – Anthony Pegram Jul 15 '11 at 17:30
8

First, you shouldn't have the : when using the ?? operator.

Second, to do what you are trying to do here without getting an error, you need to do it differently:

object objReason = cmd.ExecuteScalar();
string reason = objReason == null ? "" : objReason.ToString();

This will check whether or not your returned value is null and if it is, the second line will set reason to a blank string, otherwise it will use your returned value.

Charles Boyung
  • 2,464
  • 1
  • 21
  • 31
5

Since ExecuteScalar() returns object that might be null you should not call .ToString() since that may throw and exception.

string reason = Convert.ToString(cmd.ExecuteScalar());

This works because Convert.ToString() will convert null to string.Empty


or if you must use ?? because you really like it:

(cmd.ExecuteScalar() ?? (object)"").ToString();
hunter
  • 62,308
  • 19
  • 113
  • 113
  • Specifically, `Convert.ToString(object obj)` will convert a null to an empty string. `Convert.ToString(null)` will in fact return null. – Anthony Pegram Jul 15 '11 at 17:40
2

Just get rid of the colon.

string reason = cmd.ExecuteScalar().ToString() ?? "";

For reference, check the MSDN page.

Coeffect
  • 8,772
  • 2
  • 27
  • 42
  • 5
    Yeah -but this is still going to **fail** in the `.ExecuteScalar()` returns NULL - then your `.ToString()` is already causing the Null Reference Exception...... – marc_s Jul 15 '11 at 17:17
  • Sure, but at the time I answered the question was "how do I fix this syntax error?" – Coeffect Jul 15 '11 at 17:22
  • @Mannimacro - Except your answer is not correct. It would simply generate a different error. – Security Hound Jul 15 '11 at 17:39
  • @Ramhound: Hence me saying it fixes the _syntax error_ the original poster asked about. I was just showing how to format the ?? operator. So in that sense, it's correct. – Coeffect Jul 15 '11 at 17:45
2

When using the null-coalescing operator, you don't need the colon:

string reason = cmd.ExecuteScalar().ToString() ?? "";

As others have pointed out though, ToString() would cause a NullReferenceExcpetion to be thrown anyway...so you don't gain anything here. You'd be much better off splitting this into multiple lines:

var result = cmd.ExecuteScalar();
string reason = result == null ? "" : result.ToString();
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

You're confusing the ? conditional operator, the syntax for which looks like this:

String x = condition ? valueIfConditionIsTrue : valueIfConditionIsFalse;

with the ?? null-coalesce operator whose syntax is as follows:

String x = possiblyNull ?? valueIfPossiblyNullIsNull;

So, apart from all that... this is the part you really want:

String reason = (cmd.ExecuteScalar() ?? "").ToString();

This takes care of your exception where ToString() was causing a null-reference exception.

canon
  • 40,609
  • 10
  • 73
  • 97
1

Just use

string reason = cmd.ExecuteScalar() ??  "";
jmisra
  • 21
  • 2
  • 2
    `ExecuteScalar()` returns type `object`. As a result, your approach would result in a compiler error, "cannot implicitly convert type 'object; to 'string'." – Anthony Pegram Jul 15 '11 at 17:27