Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty string if null

Tags:

c#

asp.net-mvc

I have this in my code:

SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString()) 

It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?

/M

like image 644
Lasse Edsvik Avatar asked Nov 02 '09 09:11

Lasse Edsvik


People also ask

Should I use null or empty string?

An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Is empty string same as null in JS?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

Is string empty null C#?

C# | IsNullOrEmpty() Method 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).

IS null same as empty?

The main difference between null and empty is that the null is used to refer to nothing while empty is used to refer to a unique string with zero length. A String refers to a sequence of characters. For example, “programming” is a String.


2 Answers

(C# 2.0 - C# 5.0)

The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:

(myObject ?? "").ToString() 

Here is real-life example from my code:

 private HtmlTableCell CreateTableCell(object cellContents)  {      return new HtmlTableCell()      {          InnerText = (cellContents ?? "").ToString()                   };  } 
like image 45
Dmitriy Korobskiy Avatar answered Oct 02 '22 09:10

Dmitriy Korobskiy


(Update for C# 6.0)

If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.:

var customerId = cu.Customer?.CustomerId.ToString() ?? ""; 

One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:

// ensure (a != null) && (b != null) && (c != null) before invoking // a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null) var customerId = a?.b?.c?.CustomerId.ToString() ?? ""; 

For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:

string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : ""; 

Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.

Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer's parent class (type of cu in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.

like image 122
Groo Avatar answered Oct 02 '22 07:10

Groo