Home > Back-end >  how to use getproperty in constant c#
how to use getproperty in constant c#

Time:09-30

I am trying to get the constant value using the siting value, but I am unable to achieve that can you help me to do so

using System;
public static class Constants
{
    public static class HostServer
    {
        public static string ABC = "abc.com";
    }
    public static class WMS
    {
        public const string URL = "/create/user";
    }
}
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var x = Constants.GetType().GetProperty("ABC").GetValue(Constants, null).ToString();
        Console.WriteLine(x);
    }
}

Thanks in advance

CodePudding user response:

First of all, you need to use GetField, not GetProperty. Secondly, you should specify the binding flags since constants are essentially static. And finally, you need to use the full type name of the class since you have nested classes. With all of that, this will get you the constant value:

var x = typeof(Constants.HostServer) // <-- Use full class name here
   .GetField("ABC", BindingFlags.Public | BindingFlags.Static) // <-- binding flags
   .GetValue(null); // <-- static fields don't need an instance object
  • Related