The default value for the delegate dictionary template

Consider this code:

switch (number) { case 1: Number = (int)SmsStatusEnum.Sent; break; case 2: Number = (int)SmsStatusEnum.Delivered; break; case 3: Number = (int)SmsStatusEnum.Failed; break; default: Number = (int)SmsStatusEnum.Failed; break; } return Number; 

I have a switch case that has a default value. Therefore, if number not the result of 1,2 or 3, it will be Failed . Therefore, I convert the code into a delegate dictionary:

 var statuses = new Dictionary<int, Func<SmsStatusEnum>> { {1,()=> SmsStatusEnum.Sent}, {2,()=> SmsStatusEnum.Delivered}, {3,()=> SmsStatusEnum.Failed}, }; 

How to set default value for delegate dictionary template?

+7
dictionary c # delegates
source share
3 answers

To set the default value, you simply wrap the Dictionary in functions

 SmsStatusEnum GetStatus(int value) { Func<SmsStatusEnum> func; if (!statuses.TryGetValue(value, out func)) { // Default value return SmsStatusEnum.Failed; } return func(); } 

In this case, although I do not quite understand why you are storing Func<SmsStatusEnum> here. Does the actual calculation code use the Func<SmsStatusEnum> implementation? If so, then this is a really good example. If not, you might want to just save the Dictionary<int, SmsStatusEnum> directly

+16
source share

Sorry, but your decision looks bad for me. You do not need any additional dictionary for working with enumerations, you can create a new method and use the Enum.TryParse method:

 SmsStatusEnum GetStatus(int value) { SmsStatusEnum val; if(Enum.TryParse<SmsStatusEnum>(value.ToString(), out val)) return val; else return SmsStatusEnum.Failed; } 
+4
source share

I go this way:

 var validStatues = new int[] {1, 3, 2}; if (!validStatues.Any(x=>x == statusId)) { statusId = 0; } var statuses = new Dictionary<int, Func<SmsStatusEnum>> { {1,()=> SmsStatusEnum.Sent}, {2,()=> SmsStatusEnum.Delivered}, {3,()=> SmsStatusEnum.Failed}, {0,()=> SmsStatusEnum.Failed}, }; 
0
source share

All Articles