Can (a == 1 && a == 2 && a == 3) evaluate true in C # without multithreading?

I know this can be done in JavaScript

But is there a possible print solution for "Hurraa" under the condition below in C # without multithreading?

if (a==1 && a==2 && a==3) { Console.WriteLine("Hurraa"); } 
+5
source share
4 answers

Of course, this is the same concept as a few javascript answers. You have a side effect in the recipient of the property.

 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(); } 
+19
source

Of course, 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(); } } } 
+22
source

It depends on what a is. We could create a class so that it can behave as shown above. We need to overload the 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"); } } 
+3
source

C # with property

 static int a = 1; static int index { get { return (a++); } } static void Main(string[] args) { if (index == 1 && index == 2 && index == 3) Console.WriteLine("Hurraa"); } 
+3
source

Source: https://habr.com/ru/post/1274933/


All Articles