Search code examples
c#asp.netsystem.reflection

Get the name of a property by the value


I'd rather be using Enums but I need an easy way to display strings.

 public struct OpportunityStatus
    {
        public static string Active { get; } = "stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG";
        public static string Lost { get; } = "stat_LOjFr8l9IG0XQ0Wq23d0uiXe3fDEapCW7vsGECZnKy4";
    }

This works fine if I need to get the status code of a lost opportunity in my code without typing the status code. It helps with the readability, same as an emum.

How do I do it in reverse though? How can I get the property name by the string value:

    public static object FindByStatusCode(string statusCode)
    {
        return typeof(LeadStatus)
           .GetProperty("stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG");
    }

Should return "Active"


Solution

  • Yes, this is possible using reflection, but be aware that it can be very slow...

        public static string GetPropertyByValue(Type staticClass, string value)
        {
            var typeInfo = staticClass.GetProperties(BindingFlags.Static | BindingFlags.Public)
                                                    .Where(p => string.Compare(p.GetValue(null) as string, value) == 0)
                                                    .FirstOrDefault();
            return typeInfo?.Name;
        }
    

    This will return the name of a static property with a certain value. It requires that the property be static.

    You can call it like this:

    var name = GetPropertyByValue(typeof(OpportunityStatus), "stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG");
    

    Where name will equal Active.