Question

Each union case in discriminated union type gets a tag number

type Result<'TSuccess,'TFailure> = 
   | Success of 'TSuccess
   | Failure of 'TFailure

let cases = FSharpType.GetUnionCases typedefof<Result<_,_>>
for case in cases do
    case.Tag

From looking at compiled code it's generated by compiler and constant depending on the order of cases. So Success is 0 and Failure is 1.

  • Is the tag number always generated based on the order? Is this in F# specs?
  • Is it possible to provide custom tag number, so that if the order changes or I put another case in the middle, between Success and Failure, their tag numbers don't change?

I'm trying to setup protobuf-net to serialize discriminated union by creating custom type model and adding Success and Failure as sub-types of Result. But for that to work need to specify the for each class, which must remain constant. I was hoping to automate the setup, but would need to be able to have a number relate to each type and for that relatonship to never change. Tag seems to be perfect, if it can be hardcoded in discriminated union definition.

Was it helpful?

Solution

So we can just read the spec:

If U has more than one case, it has one CLI nested type U.Tags. The U.Tags type contains one integer literal for each case, in increasing order starting from zero.

(section 8.5.4)

So it seems like you can rely on the order of the elements, but inserting new elements will cause new numbers to be created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top