0
namespace Test
{
    public struct ABC
    {
        public const int x = 1;
        public const int y = 10;
        public const int z = 5;
    }
}

namespace search
{
    int A = 1;
    how to search A in struct and get variable name 'x'
}
2
  • 6
    While this is likely possible with reflection, there's a pretty good chance that your object model is wrong if you even need to do this. Can you give a non-contrived example of what you're looking to accomplish? Commented May 7, 2014 at 19:52
  • Are you not allowed to change that struct? You'd probably be better off using array to loop through. Anywho, take a look at this: stackoverflow.com/questions/5873892/… Commented May 7, 2014 at 20:00

3 Answers 3

2

I think better option is to turn it to a enum.

public enum ABC
{
    x = 1,
    y = 10,
    z = 5
}

Then you can use Enum.GetName.

string name = Enum.GetName(typeof(ABC), 1);//Will return x
Sign up to request clarification or add additional context in comments.

Comments

0

Using LINQ and Reflection, you can do the following:

var field = typeof (ABC)
        .GetFields()
        .FirstOrDefault(x =>x.FieldType == typeof(int) && (int)x.GetValue(null) == A);

if(field != null) Console.WriteLine(field.Name);

Comments

0
        static void Main(string[] args)
    {
        FieldInfo[] myFields = typeof(ABC).GetFields();
        int A = 1;

        foreach (FieldInfo field in myFields)
            if ((int)field.GetRawConstantValue() == A)
                Console.WriteLine(field.ToString());

        Console.ReadKey();
    }

    public struct ABC
    {
        public const int x = 1;
        public const int y = 10;
        public const int z = 5;
    }

I believe this would fit your needs, however I do think you should tell us what you're trying to do (your actual scenario), so we can better assist you.

Edit: don't forget to include System.Reflection

2 Comments

if there is any field of different type that is not convertible to int, this code will throw an InvalidCastException
OP didn't mention anything to think otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.