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

前端 未结 9 1204
鱼传尺愫
鱼传尺愫 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: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"
    }
    

提交回复
热议问题