C #, can I transfer the source code of a word from the constructor?

Here is my code right now. But I would like to move these "Add" from the constructor. Can we initialize the Dictionary when we new this? or you have another idea. Basically I want to define a few characters that are used in many places.

 public class User { public enum actionEnum { In, Out, Fail } public static Dictionary<actionEnum, String> loginAction = new Dictionary<actionEnum, string>(); public User() { loginAction.Add(actionEnum.In, "I"); loginAction.Add(actionEnum.Out, "O"); loginAction.Add(actionEnum.Fail, "F"); } ..... } 
+4
source share
1 answer

You can use C # 3 collection initializer syntax :

 public static Dictionary<actionEnum, String> loginAction = new Dictionary<actionEnum, string> { { actionEnum.In, "I" }, { actionEnum.Out, "O" }, { actionEnum.Fail, "F" } }; 

Note, by the way, that the dictionary is volatile; any code can add or remove values.

+16
source

Source: https://habr.com/ru/post/1309442/


All Articles