I have a class called Department
which contains some constants, I need a method to check if a given value exists in this constants list.
public static class Department
{
#region Public Constants
public const int Paperback = 1;
public const int Hardcover = 2;
public const int Music = 3;
#endregion
}
Now in another class I'm using or verify/passing values like below the value.
int? Dept = 4;
var availableDepartment= Department.Exists(Dept.Value);
Here availableDepartment
should return false since 4 does not exists as department Constants.
I'm looking for an Exists
method in class to check if value 4 exists as constants or not.
Please someone help on this.
As mentioned by others, using reflection is quite an overkill and this problem can be solved in other ways.
However if for some reason you cannot use the other methods, and you must use reflection (since you explicitly tagged system.reflection), here is a way to do this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Test
{
public class Util
{
// Get the public constants of a type:
public static List<FieldInfo> GetPublicConstants(Type type)
{
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();
}
}
public static class Department
{
public const int Paperback = 1;
public const int Hardcover = 2;
public const int Music = 3;
public static bool Exists(int departmentNum)
{
var constants = Util.GetPublicConstants(typeof(Department));
foreach (var constant in constants)
{
if ((int)constant.GetRawConstantValue() == departmentNum)
{
return true;
}
}
return false;
}
}
class Program
{
private static void CheckDepartment(int departmentNum)
{
bool bExists = Department.Exists(departmentNum);
Console.WriteLine("Department {0} exists: {1}", departmentNum, bExists ? "yes" : "no");
}
static void Main(string[] args)
{
CheckDepartment(1);
CheckDepartment(4);
}
}
}
Output:
Department 1 exists: yes
Department 4 exists: no
Notes:
Util
with the method GetPublicConstants
is general and can be used for any type.Department.Exists
method I assumed all the constants are int
s, if this is not the actual case you need to cast the value to the proper type.Department.Exists
is demostrated in the test method CheckDepartment
.