Given these two discriminatory unions, I would like to get DeclaringType
from the instance instance.
type SingleCaseUnion = | One type MultiCaseUnion = | Two | Three
An example for each case will be as follows:
getDiscriminatedUnionType One = typeof<SingleCaseUnion> // true getDiscriminatedUnionType Three = typeof<MultiCaseUnion> // true
My first attempt was to get the case type and get its base class, this works because in F # a subtype is created for each case.
MultiCaseUnion.Two.GetType().BaseType = typeof<MultiCaseUnion> // true
However, for one case of union, this does not work because nested types are not created.
SingleCaseUnion.One.GetType().BaseType = typeof<SingleCaseUnion> // false
My second attempt to get a more reliable solution was to use the FSharp Reflection helpers.
FSharpType.GetUnionCases(unionValue.GetType()).First().DeclaringType
This works for all cases, but it should generate UnionCaseInfo instances for each case, which seems somewhat unnecessary.
Is there something I could miss? Sort of:
FSharpValue.GetUnionFromCase(SingleCaseUnion.One)
source share