csharplang/meetings/2017/LDM-2017-01-10.md
2017-01-31 10:38:26 -08:00

1.8 KiB

C# Language Design Notes for Jan 10, 2017

Agenda

  • Discriminated unions via "closed" types

Discriminated unions via "closed" types

There's a proposal to allow adding closed to an abstract type. This prevents inheriting from any other assembly, meaning that there would be a known set of derived types, all in the same assembly as the closed abstract type. This is somewhat similar to Scala's case classes.

At the metadata level, this could possibly be implemented by generating an internal abstract member. In fact that member could make itself useful as a property returning a tag, so we can do efficient tag-based switching.

A nice aspect is that closed can be added to existing hierarchies, adding a notion of completeness and protecting from "unauthorized" inheritance.

Adding this to existing code may lead to completeness warnings in consuming code.

In a lot of places where you switch, you don't even want completeness. It's almost like it's something you have to ask for at the switch site. Special syntax?

"Catch all" is a problem. Often I want to have a catch all even as I want to be told if there's a new case. We could say that if there's a closed type, then you need to be complete in a switch. Which you can be with a default, but then you won't know if there's a new case: it's up to you.

Enums: We could allow closed on those, and then eliminate the explicit conversion to it, as well as arithmetic. Switching could generate a default that throws, in case someone monkeyed an illegal value in there.

A closed enum wouldn't get much value out of being an enum, since we don't want operators to work on them. We could consider making them not be enums from the runtime perspective.

Conclusion

An interesting approach to discriminated unions that might be a better fit with the spirit of C#.