using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Modbus.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) throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "{0} is not a valid option for this discriminated union instance.", DiscriminatedUnionOption.A)); 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) throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "{0} is not a valid option for this discriminated union instance.", DiscriminatedUnionOption.B)); return this.optionB; } } /// /// Gets the discriminated value option set for this instance. /// public DiscriminatedUnionOption Option { get { return 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 = null; switch (Option) { case DiscriminatedUnionOption.A: value = A.ToString(); break; case DiscriminatedUnionOption.B: value = B.ToString(); break; } return value; } } }