I need to pass values to a method, along with an indication of whether each value is specified or unspecified, since null is a valid value itself, and therefore cannot be interpreted as “unspecified”.
I took the generic approach and created a simple container for such values (see below), but is this the right way to go? Are there better ways to approach this problem – e.g. does a class like this already exist in the framework?
public struct Omissible<T>
{
public readonly T Value;
public readonly bool IsSpecified;
public static readonly Omissible<T> Unspecified;
public Omissible(T value)
{
this.Value = value;
this.IsSpecified = true;
}
}
The method signature could look like the following, allowing the caller to indicate that certain values shouldn’t be updated (unspecified), others should be set to null/another value (specified).
public void BulkUpdate(int[] itemIds,
Omissible<int?> value1, Omissible<string> value2) // etc.
This is the best one can theoretically do. In order to distinguish a general
Tfrom a “Tornull” you need one possible state more than a variable of typeTcan hold.For example, a 32 bit int can hold
2^32states. If you want to save anullvalue in addition you need2^32 + 1possible states which does not fit into a 4 byte location.So you need a
boolvalue in addition. (Theoretically speaking you just needlog2(2^32 + 1) - 32bits for theOmissible<int>case, but an easy way to store this is abool).