Alternative design for closed keyword and union types #9509
-
I have just read these designs:
Personally, I think elegance, terseness and reducing cognitive overload are by far the most important drivers when you are designing a programming language (after non breaking changes). My personal opinion is that adding another keyword/modifier ('closed') and introduce a complete new concept ('case types and case classes, incl syntax) is totally not respecting above drivers. The closed keyword is not terse, its not elegant, and it does not reduce cognitive overload for example. One thing I really like/understand is that when you want to have some kind of discriminated unions in C#, its must be typed/types. So you need to have predefined/declared types in order to create a union / set. So why not trying to create 1 concept, steal it from another language so its pretty common (Typescript) and try to respect most of the drivers from above. I am sure I am thinking way too simplistisch here, but sometimes I think its good that somebody is giving you feedback that you might to too far or too complex here. Always try to make it very simple, without adding too much stuff. My basic idea: TypeScript: C#: // records
record Animal {}
record Dog : Animal
record Cat : Animal
// create a closed set of records
type MyAnimals = { Dog, Cat }
// or classes
class Animal {}
class Dog : Animal
class Cat : Animal
// create a closed set of classes
type MyAnimals = { Dog, Cat }
// or enums
enum Animal { Dog, Cat, Bird }
// create a closed set of enums
type MyAnimals = { Dog, Cat }
static string MakeSound(MyAnimals animal) => animal switch
{
// exhaustive
}
etc I am sure there are lots of things I miss here since I am not a fulltime lang designer or compiler writer but I really care about the fact that C# will stay or tries to become simple and intuitive. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
The nominal type union syntax is already pretty terse for existing case types:
That is different from public sealed interface Shape { }
public record Circle(float radius) implements Shape { }
public record Square(float side) implements Shape { }
public record Rectangle(float length, float height) implements Shape { } |
Beta Was this translation helpful? Give feedback.
-
Closed classes are there to provide a simple path forward for existing closed class hierarchies. Even if you don't have an IDE that can refactor everything for you, it's a very straightforward two-step plan:
Presto, you can now add new derived types and the compiler will actually warn you where exactly you have to handle them. |
Beta Was this translation helpful? Give feedback.
The nominal type union syntax is already pretty terse for existing case types:
That is different from
closed
which is intended to declare a closed type hierarchy, or one with a known set of direct descendants. That syntax is borrowing from Java, which uses thesealed
keyword: