How to check if a given value exists in list of constants

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.

5

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:

  1. class Util with the method GetPublicConstants is general and can be used for any type.
  2. In Department.Exists method I assumed all the constants are ints, if this is not the actual case you need to cast the value to the proper type.
  3. The usage of Department.Exists is demostrated in the test method CheckDepartment.

Live demo

2

If you can’t use enum (which nonetheless should be the preferred way of doing such things), how about the straight forward way of implementing a static method in the static class Department? No need for reflection, because if you add an additional value to the Department class you can also adapt the Exists method …

public static class Department {

  public const int Paperback = 1;
  public const int Hardcover = 2;
  public const int Music = 3;
  
  public static bool Exists(int val) {
    return val == Paperback || val == Hardcover || val == Music;
  }
}

which you then can call via

Department.Exists(3);  //returns true
Department.Exists(27); //returns false

See also this fiddle

You can use an enum and set it to your constants.

public static class Department {

    private enum DepartmentEnum
    {
        Paperback = 1,
        Hardcover = 2,
        Music = 3,
    }

    public const int Paperback = (int)DepartmentEnum.Paperback;
    public const int Hardcover = (int)DepartmentEnum.Hardcover;
    public const int Music = (int)DepartmentEnum.Music;
  
    public static bool Exists(int value) {
        return Enum.IsDefined<DepartmentEnum>(value);
    }

}

This solution relies on you defining each constant both in the class and in the enum. I don’t know what is your use case nor the reason for your constraint on not using enums, but this should work, unless you have some other constraint you did not mention in the question.

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật