1

How do I check if a string is null and set it to some value if it is?

Like in SQL,

isnull(string, 0)

3 Answers 3

13

You could test for null:

if (s == null)
   s = "Hello";

or use the null coalescing operator:

string null_s = null;
string non_null_s = null_s ?? "Hello";

If you want to catch empty strings too, then you could use the IsNullOrEmpty test:

if (String.IsNullOrEmpty(s))
   s = "Hello";
Sign up to request clarification or add additional context in comments.

2 Comments

A little side note, string.IsNullOrEmpty() would mean you can't use ??, only the if statement (or if-else).
as another side note, if you're asking questions about "null", then it might be worth spending a little time on a C# primer/tutorial - just so you can understand the basics of what C# means by objects, references, instances, etc - each language is different (SQL is very different to C#) and reading up on a few basics might save you some from some frustration.
3
string myString = null;
string isNullString = myString == null ? "0" : myString;

Comments

2

If you are using .Net 4.0 you can use string.IsNullOrWhiteSpace method also.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.