Reputation: 145
Is there a recommended best practice for checking for NULL and empty (anything else?) before doing string manipulations, in C#? Specifically, I needed to call Replace and Trim on a string, but find that doing that on a NULL string throws. So is there a better format than the following?
tmp = (tmp == null) ? null : tmp.Replace("TOKEN", "").Trim();
Upvotes: 2
Views: 196
Reputation: 155250
Use String.IsNullOrWhitespace
in .NET 4.0 or later, or String.IsNullOrEmpty
in .NET 3.x.
String temp = ...
if( !String.IsNullOrWhitespace( temp ) ) {
temp = temp.Replace("TOKEN", "").Trim();
}
C# 6.0 adds the ?.
operator, which is "null-safe", it just returns null and skips the rest of the navigation expression:
String temp = ...
temp = temp?.Replace("TOKEN", "").Trim();
As I remarked in my comment, if you're accessing a database using ADO.NET (DataSet
, DataTable
, IDataReader
, etc) then you should check for DBNull
which is used to indicate SQL NULL
values, which are distinct from null
in C#:
using( IDataReader rdr = command.ExecuteReader() ) {
while( rdr.Read() ) {
String value = rdr.IsDBNull( someColumnIndex ) ? null : rdr.GetString( someColumnIndex );
}
}
Or:
DataTable table = ...
foreach( DataRow row in table.Rows ) {
if( row["someColumn"] != DBNull.Value ) {
String value = (String)row["someColumn"];
// do stuff
}
}
Upvotes: 8