Reputation: 4021
Simple c# console application to check how to get fields of an unknown object.
public class A
{
public int id;
public string name;
public string desc;
}
class Program
{
static void Main(string[] args)
{
A a = new A();
getProp(a);
Console.ReadKey();
}
static object getProp(object o)
{
Type type = o.GetType();
PropertyInfo[] pros = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//Do Something
return null;
}
}
I am not getting any fields. pros
has no value inside it. I have to get the field names of the object o
.
Upvotes: 0
Views: 278
Reputation: 13003
The members which you're trying to fetch are not properties, but fields. Try the following:
var fields = typeof(A).GetFields();
Or:
static FieldInfo[] GetFields(object o)
{
Type type = o.GetType();
FieldInfo[] fields = type.GetFields();
return fields;
}
And in order to grab the object's fields values:
var fields = GetFields(obj);
foreach(var field in fields)
{
Console.WriteLine(field.GetValue(obj));
}
From MSDN:
Type.GetFields Method
Returns all the public fields of the current Type.
Upvotes: 1