0

Elements.cs

namespace Tutorials
{
    public static class Elements
    {
        public const string element1 = "asd";
        public const string element2 = "qwe";
        public const string element3 = "zxc";
    }
}

Program.cs

namespace Tutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string FindThisField = "element1";
            string FromThisStaticClass = "Elements";

            string result = GetFieldFromStaticClass(FromThisStaticClass, FindThisField);
            Console.WriteLine(result);
        }

        public static string GetFieldFromStaticClass(string typeName, string fieldName)
        {
            Type t = Type.GetType(typeName);

            FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);
            string value;
            foreach (FieldInfo fi in fields)
            {
                if (fi.Name == fieldName)
                {
                    value = fi.GetValue(null).ToString();
                    return value;
                }
            }
            return null;
        }
    }
}

I can get the constants without any problems, but I also want to be able to get the Type t from a string.

Type t = Type.GetType(typeName);

Is there any better way to do it?

Edit:

I solved the problem by making the following change:

FromThisStaticClass = "Tutorials.Elements";
  • 1
    `Type.GetType()` requires a fully qualified name. Include the namespace name (of `Elements`) in `FromThisStaticClass`. – PMF Jun 14 '21 at 11:36
  • Does this answer your question? [Get value of constant by name](https://stackoverflow.com/questions/33477163/get-value-of-constant-by-name) and [Get value of static field](https://stackoverflow.com/questions/1340438/get-value-of-static-field) and [C# - Faster way to get set public static fields instead of using Reflection.SetValue / GetValue](https://stackoverflow.com/questions/64799655/c-sharp-faster-way-to-get-set-public-static-fields-instead-of-using-reflection) –  Jun 14 '21 at 11:37
  • 1
    @OlivierRogier He appears to fail on getting the type already. – PMF Jun 14 '21 at 11:37
  • 1
    For `const` see [this topic](https://stackoverflow.com/q/33477163/1997232). – Sinatr Jun 14 '21 at 11:38
  • @PMF Indeed, I voted too quickly based on the recurrent question title and don't see that field is const, thus it is not a variable field strictly speaking, being a particular type of field: "*[Constant](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const) fields and locals aren't variables and may not be modified*". Updated, thanks. –  Jun 14 '21 at 11:39

0 Answers0