Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand way to denullify a string in C#?

Tags:

string

c#

.net

null

Is there a shorthand way to denullify a string in C#?

It would be the equivalent of (if 'x' is a string):

string y = x == null ? "" : x;

I guess I'm hoping there's some operator that would work something like:

string y = #x;

Wishful thinking, huh?

The closest I've got so far is an extension method on the string class:

public static string ToNotNull(this string value)
{
    return value == null ? "" : value;
}

which allows me to do:

string y = x.ToNotNull();

Any improvements on that, anyone?

like image 621
Oundless Avatar asked Apr 21 '10 10:04

Oundless


People also ask

How do you indicate that string might be null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

IS NOT null shorthand C#?

The null-coalescing operator ( ?? ) is like a shorthand, inline if/else statement that handles null values. This operator evaluates a reference value and, when found non-null, returns that value. When that reference is null , then the operator returns another, default value instead.

Is string empty null c#?

C# | IsNullOrEmpty() Method It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String. Empty (A constant for empty strings).


1 Answers

This will work:

string y = x ?? "";

See http://msdn.microsoft.com/en-us/library/ms173224.aspx

like image 79
Hans Kesting Avatar answered Oct 11 '22 23:10

Hans Kesting