S. Vikneshwar
S. Vikneshwar

Reputation: 91

Difference: Between textbox = "" and Null

What is the difference between

TextBox1.Text = null;

and

TextBox1.Text = "";

both clears or nullifies the textbox, but is there any particular difference?

Upvotes: 0

Views: 295

Answers (3)

AshokD
AshokD

Reputation: 442

TextBox1.Text is property available in TextBox class, where in setter null check is added before assigning the value. Some thing simpler to below code.

string txt= string.Empty;



 public string Text
    {
        get {
            return txt;
        }
        set
        {
            if (string.IsNullOrEmpty(value))
            {
                txt = string.Empty;
            }
            else
            {
                txt = value;
            }
        }
    } 

Upvotes: 0

Curtis
Curtis

Reputation: 103348

Assuming you are referring to ASP.NET Web Forms:

"" is an actual string, which has a length of 0.

null, means that the string variable points to nothing. And therefore will not produce a value.

When the TextBox is rendered into HTML, there will be no difference.

Upvotes: 0

Uwe Keim
Uwe Keim

Reputation: 40736

Assuming you are refering to WinForms, this is an excerpt from ILSpy of System.Windows.Forms.Control:

public virtual string Text
{
    get
    {
        // ...
    }
    set
    {
        if (value == null)
        {
            value = "";
        }

        // ...
    }
}

So as you can see, both passing null and string.Empty results in assigning string.Empty to the control.

If you are refering to ASP.NET (WebForms), the same applies, as you can see from this excerpt of System.Web.UI.WebControls.TextBox:

public virtual string Text
{
    get
    {
        string text = (string)this.ViewState["Text"];
        if (text != null)
        {
            return text;
        }
        return string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}

Here, in the get part, it returns string.Empty for a null value, too.

My conclusion would be that there is no practical difference for your daily use of the TextBox control.

Upvotes: 4

Related Questions