Hello guys,
How can I refactor that code ?
public enum enum1
{
value1 = 0x01,
value2 = 0x02,
value3 = 0x03,
value4 = 0x04,
value5 = 0x05,
UNKNOWN = 0xFF
}
class class1
{
private const string STR_VALUE1 = "some text description of value1";
private const string STR_VALUE2 = "some text description of value2";
private const string STR_VALUE3 = "some text description of value3";
private const string STR_VALUE4 = "some text description of value4";
private const string STR_VALUE5 = "some text description of value5";
private const string STR_VALUE6 = "some text description of unknown type";
public static string GetStringByTypeCode(enum1 type)
{
switch(type)
{
case enum1.value1:
return STR_VALUE1;
case enum1.value2:
return STR_VALUE2;
case enum1.value3:
return STR_VALUE3;
case enum1.value4:
return STR_VALUE4;
case enum1.value5:
return STR_VALUE5;
default:
return STR_VALUE6;
}
}
}
PS: there are many enum1...enumX and GetStringByTypeCode(enum1) ... GetStringByTypeCode(enumX) methods.
EDIT: I refactored it this way:
namespace ConsoleApplication4
{
public enum enum1
{
value1 = 0x01,
value2 = 0x02,
value3 = 0x03,
value4 = 0x04,
value5 = 0x05,
UNKNOWN = 0xFF
}
class class1
{
static Dictionary<enum1, string> _dict;
static class1()
{
_dict = new Dictionary<enum1, string>();
_dict.Add(enum1.value1, "some text description of value1");
_dict.Add(enum1.value2, "some text description of value2");
_dict.Add(enum1.value3, "some text description of value3");
_dict.Add(enum1.value4, "some text description of value4");
_dict.Add(enum1.value5, "some text description of value5");
_dict.Add(enum1.UNKNOWN, "some text description of unknown type");
}
public static string GetStringByTypeCode(enum1 type)
{
string result = string.Empty;
try
{
_dict.TryGetValue(type, out result);
}
catch
{
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(class1.GetStringByTypeCode(enum1.value4));
Console.ReadKey();
}
}
}