is there recommended best practice checking null , empty (anything else?) before doing string manipulations, in c#? specifically, needed call replace , trim on string, find doing on null string throws. there better format following?
tmp = (tmp == null) ? null : tmp.replace("token", "").trim();
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 ?. operator, "null-safe", returns null , skips rest of navigation expression:
string temp = ... temp = temp?.replace("token", "").trim(); as remarked in comment, if you're accessing database using ado.net (dataset, datatable, idatareader, etc) should check dbnull used indicate sql null values, distinct 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"]; // stuff } }
Comments
Post a Comment