Hi everyone.
I would like if .net core incorporated Rust-style enumerations. Currently you can make a switch using pattern matching with classes, but for the specific case of enumerations I think this type of construction would be very interesting since it would avoid having to create classes and it would be a more natural way for a value of a enumeration to have a payload associated.
What do you think?
For example, this code is in Rust:enum WebEvent {
PageLoad,
PageUnload,
KeyPress(char),
Paste(String),
Click { x: i64, y: i64 },
}
There is a proposal about “enum classes”/discriminated unions in C# and In think they’re on the roadmap for C# 10, I’m not 100% sure though.
Edit: just looked up, they’re an active proposal at https://github.com/dotnet/csharplang/blob/master/proposals/discriminated-unions.md
Wonderful, thanks!
I’ve never used Rust. What’s the intention of that enum pattern?
Seems like it wouldn’t be hard to split that into a class with an enum-valued property plus other “normal” properties?
When I think of an event, I would consider that a “data packet”, and I’d never expect that to be covered by an enum type, so I’m curious how Rust handles it differently vs using a class.
The problem with creating a class with N properties and an Enum is that when making the switch you have to take a value from the class depending on the value of the enumerated one, so you would have to return some base type such as object or some interface or base class that was common to all payloads, so you would have to cast later.
For example, currently in C # to add additional data to an Enum I can only think of two ways. Create an extension method or declare Attributes that can be inspected by reflection. Even so, it would not be ergonomic if for example the first Enum payload I want to save a string and a class in another.
You can create some kind of cache but it is still less efficient and less ergonomic.
The current pattern matching in C # would force to create a class for each value of the enumeration which is too much code and also is not the most efficient.
For example in Rust you can use pattern matching in this way
let event = WebEvent::KeyPress(‘A’);
match event
{
KeyPress(character) =>
{
println!("Character {}", character);
},
Paste(message) =>
{
}
...
}
C# devs
null reference exceptions