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");
}
Yes, it can. The question is — Can (a==1 && a==2 && a==3) ever evaluate to true? The answer is — Yes.
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.
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();
}
}
}
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();
}
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With