Develope Cruz
Develope Cruz

Reputation: 373

C# GetProperties() doesnt return all of them

I have these classes

class Foo () {
 public string propA;
 public Bar propB
}

class Bar {
 public string propC;
}

When I am trying Foo.GetType().GetProperties() it only returns propA.

What am I missing here;

Upvotes: 0

Views: 1688

Answers (3)

Julius R
Julius R

Reputation: 155

You need to understand difference between Field and Property, there's a good explaination in this answer: https://stackoverflow.com/a/295109/929910

And your example also looks odd, because GetProperties should return 0 results as your class only has fields and not properties. Proper example would look like this:

void Main()
{
    var props = typeof(Foo).GetProperties();
}
class Foo {
    public string propA;
    public Bar propB;
}
class Bar
{
    public string propC;
}

And props would contain 0 elements. But if you would call

    var fields = typeof(Foo).GetFields();

fields would contain both fields propA and propB.

Upvotes: 2

ProgrammingLlama
ProgrammingLlama

Reputation: 38880

Your class currently contains fields, not properties.

Field example:

private string _myField;

Property examples:

public string MyField {get;set;}
public string MyField { get { return _myField; } set { _myField = value; } }
public string MyField => _myField;

Because they are different things, there are different methods to reflect them. You can either get fields and properties separately:

foreach (var field in type.GetFields())
{

}

foreach (var property in type.GetProperties())
{

}

or you can get "members" and for each member, determine if it's a property or field:

foreach (var member in type.GetMembers(System.Reflection.BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.GetField))
{
    if (member is FieldInfo fi)
    {

    }
    else if (member is PropertyInfo pi)
    {

    }
}

** If you want to find properties or fields you can set, you might need to change the binding flags.

Note that, from a design perspective, fields should probably be protected or private. To expose data from your class, you should ideally use properties. More on that here.

Upvotes: 4

currarpickt
currarpickt

Reputation: 2302

In this case, both classes have fields. So, you need to use GetType().GetFields().

class Foo {
 public string propA;
 public Bar propB;
}

class Bar {
 public string propC;
}

If you want to use GetType().GetProperties(), then the classes become:

class Foo {
 private string _propA;
 public string PropA { get { return _propA; } set { _propA= value; } }

 private Bar _propB;
 public Bar PropB { get { return _propB; } set { _propB= value; } }
}

class Bar {
 public string propC;
}

Upvotes: 1

Related Questions