Skip to content

Instantly share code, notes, and snippets.

@sohjsolwin
Created June 13, 2019 13:00
Show Gist options
  • Save sohjsolwin/1b7246f34681621298b35744b6a19ad6 to your computer and use it in GitHub Desktop.
Save sohjsolwin/1b7246f34681621298b35744b6a19ad6 to your computer and use it in GitHub Desktop.
Union type for bitwise comparisons
var leadSource = LeadSource.A;
var union = LeadSource.A | LeadSource.B | LeadSource.C;
Console.WriteLine(union & leadSource); //true
Console.WriteLine(union & LeadSource.B); //true
Console.WriteLine(union & LeadSource.C); //true
Console.WriteLine(union & LeadSource.D); //false
var result = "default";
if (union & leadSource)
{
result = "test";
}
else if ((LeadSource.C | LeadSource.D ) & leadSource)
{
result = "test2";
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
namespace Scrap
{
public class Union<T> : IEnumerable<T> where T : IEquatable<T>
{
internal ImmutableHashSet<T> _internalSet;
private Union(T input)
{
_internalSet = new[]{input}.ToImmutableHashSet();
}
private Union(IEnumerable<T> input)
{
_internalSet = input.ToImmutableHashSet();
}
public static Union<T> From(IEnumerable<T> input)
{
return new Union<T>(input);
}
public static Union<T> From(T input)
{
return new Union<T>(input);
}
private static Union<T> From(Union<T> left, T right)
{
var combined = left.AsEnumerable().Append(right);
return new Union<T>(combined);
}
private static Union<T> From(Union<T> left, Union<T> right)
{
var combined = left.AsEnumerable().Concat(right);
return new Union<T>(combined);
}
public IEnumerator<T> GetEnumerator()
{
return _internalSet.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _internalSet.GetEnumerator();
}
public static Union<T> operator |(Union<T> left, T right) => From(left, right);
public static Union<T> operator |(T left, Union<T> right) => right | left;
public static Union<T> operator |(Union<T> left, Union<T> right) => From(left, right);
public static bool operator &(Union<T> left, T right) => left.Contains(right);
public static bool operator &(T left, Union<T> right) => right & left;
public bool Contains(T value)
{
return this & value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment