Search code examples
c#if-statementcomparisoncomparison-operators

use comparison operators continuous in c#


Hello my name is parsa and I'm a c# programmer i want to use comparison operators continuous for example imagine we have three Variables named V1,V2,V3

            Random rnd = new Random();
            int V1 = rnd.Next(1,5), V2 = rnd.Next(1, 5), V3 = rnd.Next(1, 5);

each of them is equal to a random number between 1 and 4 then we want to see are they equal together and are they equal to 3 ? we have to use this code

    if(V1 == V2 && V1 == V3 && V1 == 3)
        //body

if i want to use it such as this this it will be get me a error !

    if(V1 == V2 == V3 == 3)
        //body

can i use it such as code i wrote ?


Solution

  • Unfortunately, you can't do this in C#; however, if you are comparing a variable against several patterns (like constant patterns or type patterns), (since C# 9.0) you can write

    if(v is a or b or c)
    

    Note that you can use C# 9.0 in Visual Studio 16.8 or later. It was introduced together with .NET 5. You can use most of the C# 9.0 features (including pattern matching) in older framework versions by adding a LangVersion tag to the *.csproj manually.

    <PropertyGroup>
        ...
        <LangVersion>latest</LangVersion>
    </PropertyGroup>
    

    See also: What's new in C# 9.0 / Pattern matching enhancements (Microsoft Docs)