Ajax3.14
Ajax3.14

Reputation: 1695

How to set the value of string to null

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.

Upvotes: 16

Views: 94067

Answers (7)

Tim Melton
Tim Melton

Reputation: 329

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);
            }

Upvotes: 0

Wesam
Wesam

Reputation: 1050

assign it to this value will make it a null ,(chose the right sql datatype , here its double )

    System.Data.SqlTypes.SqlDouble.Null

Upvotes: 0

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

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 to empty rather than null. To avoid exceptions later. If you have to read and write a lot of strings you'll have null value exceptions all over the place. Or you'll have a ton of if(!string.isNullorEmpty(string)) which get annoying

Upvotes: 31

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

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();

Upvotes: 0

Joel B
Joel B

Reputation: 13110

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).

Upvotes: -1

Seth Flowers
Seth Flowers

Reputation: 9190

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#?

Upvotes: 16

Wormbo
Wormbo

Reputation: 4992

null is not a special string value (there's String.Empty for ""), but a general object literal for the empty reference.

Upvotes: 4

Related Questions