Search code examples
c#if-statementuipathuipath-studio

Difference between "" (Empty String) and isNot Nothing?


I am working on a condition where I have to validate whether the argument is empty or not. Lets assume that argument is Email. I have to check whether the inwards argument Email is empty or not. I can do it in several way but I am not sure which one to proceed with.

I am thinking to check from following statement:

1.Email = "" to check if email is empty string or not. 2. Email isNot Nothing

I wanna know the difference of these two functionality. If there are more function or argument related to validating empty string, You can write that too.

Thanks.


Solution

  • String is a reference type, which means it can have a null reference

    Eg

    string myString = null;
    

    It can also be empty, which is to say, there is a reference to it, and it has 0 character length

    Eg

    string myString = "";
    // or
    string myString = string.Empty;
    

    And just for completeness, it can also have white space

    Eg

    string myString = "   ";
    

    You can check for null like so

    if(myString == null)
    

    You can check for empty

    if(myString == "")
    
    // or
    
    if(myString == string.Empty)
    

    You can check for both, not null and not empty

    if(myString != null && myString != string.Empty)
    

    You could use Null conditional Operator with Length to check both is not null and not empty

    if(myString?.Length > 0)
    

    Or you can use the built in string methods, to make it a little easier

    String.IsNullOrEmpty(String) Method

    Indicates whether the specified string is null or an empty string ("").

    if(string.IsNullOrEmpty(myString))
    

    String.IsNullOrWhiteSpace(String) Method

    Indicates whether a specified string is null, empty, or consists only of white-space characters.

    if(string.IsNullOrWhiteSpace(myString))
    

    Note : It's worth noting, that IsNullOrWhiteSpace generally more robust when checking user input