by Mikael Henriksson
6. February 2010 16:43
I sometimes have to test outgoing messages before we send them out. Since we work in the mobile industry we need to communicate with mobile phones and alas most countries have legal requirements that we much abide to. Because of some Swedish and Norwegian characters like “åäö” message length etc varies. So before we change any messages in production everyone get’s to have a say on the message. To do this I have created a simple unit test where I send the SMS to everyone. though there are quite a few places where this is done and I got bored with copy pasting the numbers or using them one and one to concatenate them so I decided to use reflection for this instead.
public class Numbers
{
public const string EmployeeOne = "xxxxxxxxxx";
public const string EmployeeTwo = "xxxxxxxxxx";
public const string EmployeeThree = "xxxxxxxxxx";
public const string EmployeeFour = "xxxxxxxxxx";
public const string EmployeeFive = "xxxxxxxxxx";
public const string EmployeeSix = "xxxxxxxxxx";
public const string EmployeeSeven = "xxxxxxxxxx";
public const string EmployeeEight = "xxxxxxxxxx";
public const string EmployeeNine = "xxxxxxxxxx";
public const string EmployeeTen = "xxxxxxxxxx";
public const string EmployeeEleven = "xxxxxxxxxx";
public const string EmployeeTwelve = "xxxxxxxxxx";
}
Wow a class of constants… how beautiful! ;) Well they have their place and this is the place for a class of constants.
Instead of manually handling all the numbers when I need them all is to make good use of reflection. Most reflection starts with a type somehow and in this case we are looking for fields that are public, static and flatten hierarchy means that inherited classes protected and public constants should be searched as well.
We want the Literal (compiled values) and they should not be init (initialized using constructor only).
private const BindingFlags Flags = BindingFlags.Public |
BindingFlags.Static | BindingFlags.FlattenHierarchy;
public IEnumerable<string> GetAllNumbers(Type type)
{
FieldInfo[] fieldInfos = type.GetFields(Flags);
return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly)
.Select(fi => fi.GetValue(null).ToString());
}
If I wanted to create a tool / library around this I would probably wrap the above method with some generic.
public IEnumerable<string> GetAllNumbers<T>()
{
return GetAllNumbers(typeof (T));
}