Setting Text property to null

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

The following (C#) code snippet sets the text property of a label to null,
then tests it for null, only to find out that is isn't. Can anyone explain
why?

Label1.Text = null;
if (Label1.Text == null) {
Label2.Text = "Is null";
} else {
Label2.Text = "Is not null";
}
 
The short answer is - if you check in your debugger - when you set it to
null it is actually set to "".
 
Well I noticed that it is set to "". However, it works fine if you use a
string variable. I realize that there is a difference between a string
property, such as Text and a string variable, it just seems to me they should
behave more similarly.
--Mike
 
some properties have code under them... apparently, in this case, if you
attempt to set the Text property to a null, the code forces the value to
String.Empty.

It makes sense. The Text property of a control can't really be null. Null
is not a value. It means that "no value is known". Since the control has
to render the value, it makes sense that it would require you to provide
one.

Be happy you didn't get a runtime error.

--- Nick
 
Yup, I guess there must be code back there that makes sure Text is never
null. Thanks for your comments.
 
Back
Top