Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can (a==1 && a==2 && a==3) evaluate to true in C# without multi-threading?

Tags:

c#

I know it could be done in JavaScript

But is there any possible solution to print "Hurraa" on the condition given below in C# without multi-threading?

if (a==1 && a==2 && a==3) {
    Console.WriteLine("Hurraa");
}
like image 987
zsubzwary Avatar asked Jan 24 '18 15:01

zsubzwary


People also ask

Is it ever possible that a == 1 && a == 2 && a == 3 could evaluate to true in JavaScript?

Yes, it can. The question is — Can (a==1 && a==2 && a==3) ever evaluate to true? The answer is — Yes.

What is use of in JS?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.


3 Answers

Sure, you can overload operator == to do whatever you want.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var a = new AlwaysEqual();
            Assert.IsTrue(a == 1 && a == 2 && a == 3);
        }

        class AlwaysEqual
        {
            public static bool operator ==(AlwaysEqual c, int i) => true;
            public static bool operator !=(AlwaysEqual c, int i) => !(c == i);
            public override bool Equals(object o) => true;
            public override int GetHashCode() => true.GetHashCode();
        }
    }
}
like image 180
Jacob Krall Avatar answered Oct 23 '22 17:10

Jacob Krall


Sure, its the same concept as a few of the javascript answers. You have a side effect in a property getter.

private static int _a;
public static int a { get { return ++_a; } set { _a = value; } }
static void Main(string[] args)
{
    a = 0;
    if (a == 1 && a == 2 && a == 3)
    {
        Console.WriteLine("Hurraa");
    }
    Console.ReadLine();
}
like image 20
John Koerner Avatar answered Oct 23 '22 18:10

John Koerner


It depends on what is a. We could create a class so it's instance would behave like shown above. What we have to do is to overload operators '==' and '!='.

    class StrangeInt
    {
        public static bool operator ==(StrangeInt obj1, int obj2)
        {
            return true;
        }

        public static bool operator !=(StrangeInt obj1, int obj2)
        {
            return false;
        }
    }


    static void Main(string[] args)
    {
        StrangeInt a = new StrangeInt();
        if(a==1 && a==2 && a==3)
        {
            Console.WriteLine("Hurraa");
        }
    }
like image 3
Alex Avatar answered Oct 23 '22 17:10

Alex