C
C#2y ago
LukeJ

✅ Record for ensuring parameters

Hello. I'm currently learning Function C#, and the guy I'm currently making a demo for gave me a tip to use a record to ensure any maps of enums will be safe in that they can't compile with different entries than the record contains, so you only ever have to update that one record to never miss a map to update. He showed me this code as an example of it:
record TurnMoveA<A>(A spawnWarrior, A spawnArcher, A spawnCleric) {
public A this[TurnMove turnMove] => /* ... */;
}
record TurnMoveA<A>(A spawnWarrior, A spawnArcher, A spawnCleric) {
public A this[TurnMove turnMove] => /* ... */;
}
Generic, of course, because this would map from the TurnMove enum to anything else you wanted to map it to. I'm not actually sure how to do this in practice though, since this is the best I can come up with in implementing something that uses a record like this
public record TurnMoveBinding(TurnMove zKey, TurnMove xKey, TurnMove cKey) : ConsoleKeyBinding<TurnMove>(zKey, xKey, cKey)
{
public Option<TurnMove> this[ConsoleKey key] => key switch
{
ConsoleKey.Z => TurnMove.SpawnWarrior,
ConsoleKey.X => TurnMove.SpawnArcher,
ConsoleKey.C => TurnMove.SpawnCleric,
_ => Option<TurnMove>.None
};
}
public record TurnMoveBinding(TurnMove zKey, TurnMove xKey, TurnMove cKey) : ConsoleKeyBinding<TurnMove>(zKey, xKey, cKey)
{
public Option<TurnMove> this[ConsoleKey key] => key switch
{
ConsoleKey.Z => TurnMove.SpawnWarrior,
ConsoleKey.X => TurnMove.SpawnArcher,
ConsoleKey.C => TurnMove.SpawnCleric,
_ => Option<TurnMove>.None
};
}
You can ignore the option stuff as a part of LanguageExt. My problem here is to use it, you have to instance it, and therefore have to fill in those parameters. Those parameters are only there for parity though, and I'm not sure how you could avoid having them. What am I missing here? Before I get any messages in this vein, by the way, I'm sure there's a more sensible way of doing this, or some reason to not bother in the first place. I have been recommended to do this though, and so in the interest of learning, I want to make this work. They use it in their system, with the help of some tooling, so it's practical for me to know.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server