Sumrak
Sumrak

Reputation: 3748

f#: constant union case tag number

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.

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.

Upvotes: 2

Views: 152

Answers (1)

John Palmer
John Palmer

Reputation: 25516

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.

Upvotes: 5

Related Questions