While trying to set Validations i initially encountered some problems with checking if a textbox is null, i tried using
private void btnGo_Click(object s
The same as the difference between 0
and an empty array: everything. They’re different values. ""
is an empty string, and that’s what a blank textbox holds as text is all. null
is no value, and is not what a blank textbox has as Text
.
""
is an empty string vs null
which means "does not exist".
In your case, you first compared name
to "does not exist" which was false because name
did exist. Then you compared name
to empty string which is true because it has the value of an empty string.
null
simply means that the object (in this case, the textLogin.Text
object) does not exist. In order for this to be the case, the textLogin object cannot exist. Thus the textLogin
object is not null in this case, and thus textLogin.Text
cannot be null.
""
on the other hand means an empty string, meaning that there is nothing in the textbox's text. i.e. textLogin.Text
does not contain any characters within it.
The System.String
data type in .NET is a class, a reference type. So an empty string (""
or string.Empty
) is a reference to a value with zero length, while null
does not reference a to real value, so any attempt to access the value it references will fail.
For example:
string emptyString = "";
string nullString = null;
Console.WriteLine(emptyString.Length); // 0
Console.WriteLine(nullString.Length); // Exception!
I'd recommend you use IsNullOrEmpty (or IsNullOrWhiteSpace) in your validation code, to handle both cases:
if (string.IsNullOrEmpty(name))
{
labelError.Visiblle = true;
labelError.Text = "Field Cannot be Left Blank"
}
Simple, ""
has a valid value i.e. String.Empty
but null
doesn't have any value.
You can use IsNullOrWhiteSpace
to do text box input validation. It checks for null, empty string or white space (tab, space, etc.).
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx