using System;
using System.Diagnostics.CodeAnalysis;
namespace NModbus.Utility
{
///
/// Possible options for DiscriminatedUnion type.
///
public enum DiscriminatedUnionOption
{
///
/// Option A.
///
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "A")]
A,
///
/// Option B.
///
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "B")]
B
}
///
/// A data type that can store one of two possible strongly typed options.
///
/// The type of option A.
/// The type of option B.
public class DiscriminatedUnion
{
private TA? optionA;
private TB? optionB;
private DiscriminatedUnionOption option;
///
/// Gets the value of option A.
///
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "A")]
public TA? A
{
get
{
if (this.Option != DiscriminatedUnionOption.A)
{
string msg = $"{DiscriminatedUnionOption.A} is not a valid option for this discriminated union instance.";
throw new InvalidOperationException(msg);
}
return this.optionA;
}
}
///
/// Gets the value of option B.
///
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "B")]
public TB? B
{
get
{
if (this.Option != DiscriminatedUnionOption.B)
{
string msg = $"{DiscriminatedUnionOption.B} is not a valid option for this discriminated union instance.";
throw new InvalidOperationException(msg);
}
return this.optionB;
}
}
///
/// Gets the discriminated value option set for this instance.
///
public DiscriminatedUnionOption Option => this.option;
///
/// Factory method for creating DiscriminatedUnion with option A set.
///
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Factory method.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#a")]
public static DiscriminatedUnion CreateA(TA a)
{
return new DiscriminatedUnion() { option = DiscriminatedUnionOption.A, optionA = a };
}
///
/// Factory method for creating DiscriminatedUnion with option B set.
///
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Factory method.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#b")]
public static DiscriminatedUnion CreateB(TB b)
{
return new DiscriminatedUnion() { option = DiscriminatedUnionOption.B, optionB = b };
}
///
/// Returns a that represents the current .
///
///
/// A that represents the current .
///
public override string ToString()
{
string value = string.Empty;
switch (Option)
{
case DiscriminatedUnionOption.A:
value = A?.ToString() ?? string.Empty;
break;
case DiscriminatedUnionOption.B:
value = B?.ToString() ?? string.Empty;
break;
}
return value ?? string.Empty;
}
}
}