Max R.
Max R.

Reputation: 853

Use of the is keyword to check if a nullable is not null

I just figured out, that it is possible to use the is-keyword in C# for a null check on nullable stucts. I think it looks quite clean and is good to understand, but is it also performant? Does the interpreter has to double cast it or is it okay that way?

    static void Main(string[] args)
    {
        DateTime? test = null;

        PrintDT(test);//wont print
        test = DateTime.Now;
        PrintDT(test);//will print
    }
    private static void PrintDT(DateTime? dt)
    {
        if (dt is DateTime a)
            Console.WriteLine(a);
    }

Upvotes: 1

Views: 2182

Answers (1)

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Any tool that compiles/decompiles back to C# will give the equivalent method (release mode compile):

private static void PrintDT(DateTime? dt)
{
    if (dt.HasValue)
    {
        DateTime valueOrDefault = dt.GetValueOrDefault();
        Console.WriteLine(valueOrDefault);
    }
}

or (debug mode compile)

private static void PrintDT(DateTime? dt)
{
  DateTime valueOrDefault;
  int num;
  if (dt.HasValue)
  {
    valueOrDefault = dt.GetValueOrDefault();
    num = 1;
  }
  else
    num = 0;
  if (num == 0)
    return;
  Console.WriteLine((object) valueOrDefault);
}

So the compiler is using the nullable type syntactic sugar up front to create an optimized scenario behind the scenes.

Upvotes: 6

Related Questions