What is the difference between (“”) and (null)

前端 未结 9 1161
鱼传尺愫
鱼传尺愫 2021-01-04 18:33

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         


        
相关标签:
9条回答
  • 2021-01-04 19:03

    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.

    0 讨论(0)
  • 2021-01-04 19:04

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

    0 讨论(0)
  • 2021-01-04 19:05

    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.

    0 讨论(0)
  • 2021-01-04 19:08

    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"
    }
    
    0 讨论(0)
  • 2021-01-04 19:14

    Simple, "" has a valid value i.e. String.Empty but null doesn't have any value.

    0 讨论(0)
  • 2021-01-04 19:17

    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

    0 讨论(0)
提交回复
热议问题