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'
}
Asked
Active
Viewed 127 times
0

kemiller2002
- 113,795
- 27
- 197
- 251

user3609924
- 3
- 2
-
6While 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? – David May 07 '14 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: http://stackoverflow.com/questions/5873892/get-collection-of-values-from-structs-const-properties – sraboy May 07 '14 at 20:00
3 Answers
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

Sriram Sakthivel
- 72,067
- 7
- 111
- 189
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

Rodrigo Silva
- 432
- 1
- 6
- 18
-
if there is any field of different type that is not convertible to `int`, this code will throw an `InvalidCastException` – Selman Genç May 07 '14 at 20:02
-
1
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);

Selman Genç
- 100,147
- 13
- 119
- 184