Home > Mobile >  Testing null or empty string with this construction: s is null or ""
Testing null or empty string with this construction: s is null or ""

Time:10-22

I am very perplexed by a piece of code I came across :

string s = "this is my dummy string, it could be anything";

if (s is null or "") { // ???
   DoSomething();
}

I have never seen a string being tested in that manner. I've always only seen this :

if(string.IsNullOrEmpty(s))

I've tried googling it but the keywords involved are too generic to find any relevant result.

So, what do you think? Is this a fancy new efficient way of testing strings, or is it just some quirky habit?

CodePudding user response:

They're effectively the same:

https://docs.microsoft.com/en-us/dotnet/api/system.string.isnullorempty?view=net-5.0#remarks

Remarks

IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is String.Empty. It is equivalent to the following code:

bool TestForNullOrEmpty(string s)
{
    bool result;
    result = s == null || s == string.Empty;
    return result;
}

string s1 = null;
string s2 = "";
Console.WriteLine(TestForNullOrEmpty(s1));
Console.WriteLine(TestForNullOrEmpty(s2));

// The example displays the following output:
//    True
//    True

CodePudding user response:

To have a good judgement about the performance.
I write these codes and run them separately.
The result is insightful

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Start");
        
        string s = "this is my dummy string, it could be anything";
        
        var d1 = DateTime.Now;
        for(var i=0; i<1000000000;i  )
        {
            if(string.IsNullOrEmpty(s))
            {
                Console.WriteLine("Hello Again");
            }
        }
        Console.WriteLine("Method1: "   (DateTime.Now - d1).TotalMilliseconds);
        
        
        Console.WriteLine("End");
    }
}

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Start");
        
        string s = "this is my dummy string, it could be anything";
        
        var d2 = DateTime.Now;
        for(var i=0; i<1000000000;i  )
        {
            if (s is null or "")
            {
                Console.WriteLine("Hello Again");
            }
        }
        Console.WriteLine("Method2: "   (DateTime.Now - d2).TotalMilliseconds);
        
        Console.WriteLine("End");
    }
}

Result (Duration in miliseconds):
Method1: 2959.476
Method2: 4676.6368

  • Related