I am aware that I can set null like
string val = null;
But I am wondering the other ways I can set it to null. Is there a funcion like String.null
that I can use.
I am aware that I can set null like
string val = null;
But I am wondering the other ways I can set it to null. Is there a funcion like String.null
that I can use.
I think you are looking far String.Empty
string val = String.Empty;
Update: TheFuzzyGiggler comments are worth mentioning:
It's much better to set a
string
toempty
rather thannull
. To avoid exceptions later. If you have to read and write a lot of strings you'll havenull
value exceptions all over the place. Or you'll have a ton ofif(!string.isNullorEmpty(string))
which get annoying
You can also use the default keyword.
string val = default(string);
Here is another SO question regarding the default keyword: What is the use of `default` keyword in C#?
null
is not a special string value (there's String.Empty
for ""
), but a general object literal for the empty reference.
Obviously one more way to set something to null is to assign result of function that returns null:
string SomeFunctionThatReturnsNullString() {return null;}
string val = SomeFunctionThatReturnsNullString();
assign it to this value will make it a null ,(chose the right sql datatype , here its double )
System.Data.SqlTypes.SqlDouble.Null
I frequently run into this issue when making updates to databases. Especially when the column is a date. If you pass "" or String.Empty, the date is set to MinDate which usually displays as 01/01/1900. So Null is a preferred value when you want No date.
I have had to make sure I capture the "" case and substitute the DBNull.Value which will pass a Null value back to the DB.
if (!string.IsNullOrEmpty(this.DeletedDate)) {
db.AddParameter("newDeletedDate", this.DeletedDate);
}
else
{
db.AddParameter("newDeletedDate", DBNull.Value);
}
Depending on your application you could use string.Empty
. I'm always leery of initializing to null
as the garbage collector is great, but not perfect, and could mark your string for garbage collection if used in some way that the garbage collector can't detect (this is very unlikely though).