Odrade
Odrade

Reputation: 7609

Accessing the fields of a struct

Why does the following code produce no output?

static void Main(string[] args)
{
    FieldInfo[] fi = typeof(MyStruct).GetFields(BindingFlags.Public);
    foreach (FieldInfo info in fi)
    {
        Console.WriteLine(info.Name);
    }
}

public struct MyStruct
{
    public int one;
    public int two;
    public int three;
    public int four;
    public int five;
    public int six;
    public bool seven;
    public String eight;
}

Upvotes: 7

Views: 17883

Answers (1)

Jake Pearson
Jake Pearson

Reputation: 27717

You need to or in the instance binding as well. Change your code to:

FieldInfo[] fi = typeof(MyStruct).GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo info in fi)
{
    Console.WriteLine(info.Name);
}

Upvotes: 26

Related Questions