Is it even possible for the text property of a TextBox to be null?

I came across this code:

if (txtUPC.Text.ToString() != null)

...and wonder if this test is even valid - is it possible for the text property to be null? txtUPC is not a dynamically created control. It can be empty, of course, or contain just whitespace, but null? If so, I'd like to know how. Then again, call ToString() on the text property seems like wearing suspenders with a belt, too.

UPDATE

So it seems to me, that for me (remember: .NET 1.1, Windows CE/Compact Framework), this:

if (txtUPC.Text.Trim() != string.Empty)

...is a better test than this:

if (txtUPC.Text.ToString() != null) 

However, upon gazing even more intently at this code, it seems that either the outer or the inner gauntlet is redundant/unnecessary, anyway. Note the two shibbeleth-pronunciation-checkers that the method includes:

if (txtUPC.Text.ToString() != null) 
{
    if (txtUPC.Text.Length > 0)
    {
                    . . .
    else
    {
        MessageBox.Show("Please enter a value in the item field");
        txtUPC.Focus();
    }
}
else
{
    MessageBox.Show("Please enter a value in the item field");
    txtUPC.Focus();
}
. . .

It would seem one gatekeeper/gauntleteer would be enough - either checking this way:

if (txtUPC.Text.Trim() != string.Empty)

...or this way:

if (txtUPC.Text.Trim().Length > 0)

a?

Upvotes: 1

Views: 1005

Answers (2)

jrbeverly
jrbeverly

Reputation: 1621

The problem I see with that code is that .ToString() returns the object as a String. If in this case, the object is a String it just returns the original string (exactly as is)

Problem is if .Text is null, then the method call of .ToString() would throw a NullReferenceException.

You can see more on the .ToString override here

See this code for an example:

String str1 = "";
String str2 = null;

Console.WriteLine("Original str1: {0}", str1);
Console.WriteLine("Original str2: {0}", str2);

Console.WriteLine("ToString str1: {0}", str1.ToString());
Console.WriteLine("ToString str2: {0}", str2.ToString());

Will throw the exception on the ToString str2 line

Upvotes: 4

Jason Down
Jason Down

Reputation: 22161

I don't think it could ever be null (perhaps there is a difference between a winforms/asp.net/wpf textbox, but I don't think so). Although a better check would be:

if (String.IsNullOrEmpty(txtUPC.Text) { ... }

Or, depending on your requirements:

if (String.IsNullOrWhiteSpace(txtUPC.Text) { ... }

And yes, the .ToString() is not needed.

Upvotes: 9

Related Questions