jeudi 2 décembre 2021

Is the 'If' condition in C# supposed to behave like this? [duplicate]

I believed that doing an assignment operation inside an if condition's predicate would always result to true (in C# and in any other language). However, this doesn't happen when I tried something like this (Notice I'm just using single equals inside the If conditions):

class Program
    {
        static void Foo()
        {
            bool someVar = false;
            if (someVar = true)
                System.Diagnostics.Debug.WriteLine("This gets printed");  // as expected
        }

        static void Bar()
        {
            bool someVar = false;
            if (someVar = false)
                System.Diagnostics.Debug.WriteLine("This DOES NOT get printed");  // I exected this to be printed as well as it
        }

        static void Main(string[] args)
        {
            Foo();
            Bar();
        }
    }

Can anyone explain this? Is it because the variable someVar is being assigned a false value, its not going inside the if condition?

Aucun commentaire:

Enregistrer un commentaire