4 ms·
You can do this in C# as well, so that the final line in the snippet below causes a compile-time error, which is quite nice for many purposes: private enum
by PreInternet01 2y ago
You can do this in C# as well, so that the final line in the snippet below causes a compile-time error, which is quite nice for many purposes:
private enum Derp { }
private enum Foo { }
var derp = (Derp)12;
var foo = (Foo)99;
foo = derp;
However, this is definitely a hack, and I sort-of feel the same about the Zig solution from the article. Would be nice if languages had 'cleaner' support for this?
- gbin 2y agoIn rust it would be: struct Foo(u32); No?
- neonsunset 2y agoIn C#, a now popular choice is record struct Foo(int Value); In F#, this is instead done with // Foo and Bar cannot be assigned to each other type Foo = Foo of int type Bar = Bar of int // Foo and Bar can be assigned to each other type Foo = int type Bar = int The first variant uses single-case unions. It's a bit unfortunate that they also default to classes over structs unless you annotate them with [<Struct>], partially fixed by escape analysis though. The enum trick is the tersest and will also serialize correctly in most cases, but I have never seen anyone use it like that before.
- resonious 2y agoWhat would be your preferred syntax?
- PreInternet01 2y agoWhen using implicit typing, definitely `var foo = (int Foo)12`. Less sure what the explicit variant should look like, since parsing may be trickier, but `(int Foo) foo = 12` might work?