Home > Blockchain >  Nullable value type comparison with is-operator
Nullable value type comparison with is-operator

Time:12-09

I am wondering, if there is technically any difference between between doing a regular value comparison or doing a value comparison over the is-operator in C# when working with a nullable value type.

Given the following example:

decimal? value = null;

value < 0; // returns false

value is < 0; // returns false

Considering it both returns false, I was just wondering whether there is any technical difference in these 2 comparisons.

CodePudding user response:

In this context the is operator is part of pattern matching, meaning it will check the runtime type and then perform that operator <. < will simply do a value comparison.

For these kind of questions, a good app is sharplab.io which will show a decompiled version of the code, where the the syntactic sugar will be displayed as more plain C# code.

using System;
public class C {
    public void M() {
        decimal? value = null;
        Console.WriteLine(value < 0); // returns false
        Console.WriteLine(value is < 0); // returns false
    }
}

Becomes:

public class C
{
    public void M()
    {
        Nullable<decimal> num = null;
        Nullable<decimal> num2 = num;
        Console.WriteLine((num2.GetValueOrDefault() < default(decimal)) & num2.HasValue);
        Console.WriteLine(num.HasValue && num.GetValueOrDefault() < 0m);
    }
}

https://sharplab.io/#v2:D4AQTAjAsAUCDMACciDCiDetE UkALIgLIAUAlJtrjQCYCmAxgJYC2AhgDYD8iAblwCu9RAF5EAO0GdOAbmo0cICAE5SAzsMQAeRAAZysxAHpjyAOwBnRADMul gsXK1Grc2u6DR0xet3OBycAX1hgoA

CodePudding user response:

The is operator is used to check if the run-time type of an object is compatible with the given type or not. So it's kind of type comparison.

Regular value comparison - compares values of objects of the same type.

These are two different meanings and usages.

  • Related