Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I doubt I'd ever do this, but to answer your question, here's one way to achieve it in C# involving a little generic type inference and some abuse of operator overloading. You could write code like this:</p> <pre><code>if (x == Any.Of(1, 2)) { Console.WriteLine("In the set."); } </code></pre> <p>Where the <code>Any</code> class is defined as:</p> <pre><code>public static class Any { public static Any2&lt;T&gt; Of&lt;T&gt;(T item1, T item2) { return new Any2&lt;T&gt;(item1, item2); } public struct Any2&lt;T&gt; { T item1; T item2; public Any2(T item1, T item2) { this.item1 = item1; this.item2 = item2; } public static bool operator ==(T item, Any2&lt;T&gt; set) { return item.Equals(set.item1) || item.Equals(set.item2); } // Defining the operator== requires these three methods to be defined as well: public static bool operator !=(T item, Any2&lt;T&gt; set) { return !(item == set); } public override bool Equals(object obj) { throw new NotImplementedException(); } public override int GetHashCode() { throw new NotImplementedException(); } } } </code></pre> <p>You could conceivably have a number of overloads of the <code>Any.Of</code> method to work with 3, 4, or even more arguments. Other operators could be provided as well, and a companion <code>All</code> class could do something very similar but with <code>&amp;&amp;</code> in place of <code>||</code>.</p> <p>Looking at the disassembly, a fair bit of boxing happens because of the need to call <code>Equals</code>, so this ends up being slower than the obvious <code>(x == 1) || (x == 2)</code> construct. However, if you change all the <code>&lt;T&gt;</code>'s to <code>int</code> and replace the <code>Equals</code> with <code>==</code>, you get something which appears to inline nicely to be about the same speed as <code>(x == 1) || (x == 2)</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload