“Collection-based Containment Checks”

Or at least that’s what I think their called. Just something cool I found out and thought I’d put down here.

Instead of doing:

if (obj.GetValue() == 2 || obj.GetValue() == varA || obj.GetValue() == varB)
{
// Do the thing
}

You can do:

using System.Linq;
if (new[] { 2, varA, varB }.Contains(obj.GetValue))
{
    // Your code here
}

How useful is that! The values we check against are on the left which is great for when we end up doing Namespace.Script.Singleton.Array[someVariable].Gameobject.GetComponent<AnotherScript>().SomeDictionary[someOtherVariable].Function(moreVariables, true, false, 0)… etc.

Which also means I don’t need to grab the variable each time, making the line smaller. Probably has some efficiency tradeoff though, making a new array just for a check. But maybe that depends on the value you’re getting. Tbf I should be caching that too.

Ah well, this is readable and I like it.

Leave a comment