Using enumeration as an integer constant in C #

My question is pretty simple, but I have not found a way to implement my code the way I want. So I started to wonder if the code I want to implement is not very good. And if so, then the best way to do it.

Here he is:

class InputManager { SortedDictionary<ushort,Keys> inputList = new SortedDictionary<ushort,Keys>(); public void Add(ushort id, Keys key) {...} public bool IsPressed(ushort id) {...} } class Main { private enum RegisteredInput : ushort { Up, Down, Confirm } public Main() { InputManager manager = new InputManager(); manager.Add(RegisteredInput.Up, Keys.Q); manager.Add(RegisteredInput.Down, Keys.A); manager.Add(RegisteredInput.Confirm, Keys.Enter); } void update() { if(manager.IsPressed(RegisteredInput.Up)) action(); } } 

This code will not compile, giving errors of this kind:

The best overloaded method matching for 'InputManager.Add (ushort, Keys)' has some invalid arguments
Argument '1': cannot convert from 'RegisteredInput' to 'ushort'

If I use a listing like manager.Add((ushort)RegisteredInput.Up, Keys.Q); he will work. But since the cast should be explicit, I was wondering if it is the recommended code in C #, like in C ++, and if there is a better way to do this (for example, using const ushort for each value that I can not as much )

The best answer I've received so far is this thread , but it sounds just like a hack, I was worried.

Thanks!

+6
enums c # oop constants
source share
3 answers

Make the InputManager a generic type. IE:

 class InputManager<T> { SortedDictionary<T,Keys> inputList = new SortedDictionary<T,Keys>(); public void add(T id, Keys key) {...} public bool isPressed(T id) {...} } 
+7
source share

Why not just define a dictionary using your enumeration? Is there a reason it should be int?

 public void add(RegisteredInput id, Keys key) {...} 

In addition, it is generally recommended that publicly accessible members (methods, types, etc.) should be pascal (in other words, Add instead of Add ).

+7
source share

Implicit listing is required for Enums, I recommend this:

 public static class RegisteredInput { public const ushort Up = 0; public const ushort Down = 1; public const ushort Confirm = 2; } 
+5
source share

All Articles