Reputation:
This may sound like an odd question, and I have a feeling that the short answer is 'No'.
However, is there any way a variable could take more than one value, based on Boolean operators? For example:
//Current implementation
string Variable1 = "A";
string Variable2 = "B";
string Variable3 = "C";
//Sought after implementation
string Variable = "":
Variable = "A" || Variable = "B" || Variable = "C";
This doesn't look like it could be feasible, especially since Boolean operators can't be applied to string types, because, well... They're not Boolean.
Upvotes: 1
Views: 255
Reputation: 660128
However, is there any way a variable could take more than one value, based on Boolean operators?
Sure! Let's implement it. We'll use the ImmutableHashSet<T>
type from System.Collections.Immutable
.
struct MySet<T>
{
public readonly static MySet<T> Empty = default(MySet<T>);
private ImmutableHashSet<T> items;
private MySet(ImmutableHashSet<T> items) => this.items = items;
public ImmutableHashSet<T> Items => this.items ?? ImmutableHashSet<T>.Empty;
public MySet<T> Add(T item) => new MySet<T>(this.Items.Add(item));
public static MySet<T> operator |(T item, MySet<T> items) => items.Add(item);
public static MySet<T> operator |(MySet<T> items, T item) => items.Add(item);
public static MySet<T> operator |(MySet<T> x, MySet<T> y) => new MySet<T>(x.Items.Union(y.Items));
public static MySet<T> operator &(MySet<T> items, T item) => new MySet<T>(items.Items.Contains(item) ? ImmutableHashSet<T>.Empty.Add(item) : ImmutableHashSet<T>.Empty);
public static MySet<T> operator &(T item, MySet<T> items) => new MySet<T>(items.Items.Contains(item) ? ImmutableHashSet<T>.Empty.Add(item) : ImmutableHashSet<T>.Empty);
public static MySet<T> operator &(MySet<T> x, MySet<T> y) => new MySet<T>(x.Items.Intersect(y.Items));
}
Now we can create a variable that contains multiple values of any type, and obeys the laws of |
and &
:
var items1 = MySet<String>.Empty | "Hello" | "Goodbye" | "Whatever";
var items2 = MySet<String>.Empty | "Goodbye" | "Hello" | "Blah";
var items3 = items1 & items2;
var items4 = items1 | items2;
Console.WriteLine(String.Join(" ", items3.Items)); // "Hello Goodbye"
Console.WriteLine(String.Join(" ", items4.Items)); // "Hello Goodbye Whatever Blah"
Upvotes: 5
Reputation: 29073
Define an enum with the [Flags] attribute.
Reference: What does the [Flags] Enum Attribute mean in C#?
[Flags]
public enum PossibleValues { A = 1, B = 2, C = 4 }
var foo = PossibleValues.A | PossibleValues.B | PossibleValues.C;
Upvotes: 4