C
C#•11mo ago
potzko

C# enum deconstruction and assosiated data

hi, I want to follow the book crafting interpreters and I don't want to use the exact languadge he uses (java) to avoid copy pasting code without understanding it, I am looking at maybe using C# (I know... super far away from java), however I can't find a feature Ill prob want to use, is there a way to do rust style enum types with associated data? think something like (super super psudo code)
enum a{
twoDimantionalVector: (int, int)
position: (int, int, int)
cat: (string, string, int)
}
a value = ...
match a {
case twoDimantionalVector(X, Y);
case position(X, Y, Z) {...}
case cat(name, color, age);
}
enum a{
twoDimantionalVector: (int, int)
position: (int, int, int)
cat: (string, string, int)
}
a value = ...
match a {
case twoDimantionalVector(X, Y);
case position(X, Y, Z) {...}
case cat(name, color, age);
}
5 Replies
x0rld 👻 🎃
create a custom class probably enum are limited in c#
potzko
potzkoOP•11mo ago
I see, would I have to make the class with a slot for each and fill it with nulls where I don't have data? or how would I go about it
Thinker
Thinker•11mo ago
You can sorta hack it
public abstract record A
{
public sealed record TwoDimensionalVector(int X, int Y) : A;
public sealed record Position(int X, int Y, int Z): A;
public sealed record Cat(string Name, string Color, int Age) : A;
}
public abstract record A
{
public sealed record TwoDimensionalVector(int X, int Y) : A;
public sealed record Position(int X, int Y, int Z): A;
public sealed record Cat(string Name, string Color, int Age) : A;
}
var value = a switch
{
A.TwoDimensionalVector(var x, var y) => ...,
A.Position(var x, var y, var z) => ...,
A.Cat(var name, var color, var age) => ...,
};
var value = a switch
{
A.TwoDimensionalVector(var x, var y) => ...,
A.Position(var x, var y, var z) => ...,
A.Cat(var name, var color, var age) => ...,
};
x0rld 👻 🎃
there is a nuget package to have java like enum in c# let me find that https://github.com/ardalis/SmartEnum
potzko
potzkoOP•11mo ago
That would work, ty 🙂
Want results from more Discord servers?
Add your server