Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does GetFields() not return anything?

Tags:

c#

I am trying to retrieve the public properties of an object but it is returning nothing. Can you tell me what I'm doing wrong.

public class AdHocCallReportViewModel : ReportViewModel
{
    public string OperatorForCustEquipID { get; set; }
    public string OperatorForPriorityID { get; set; }
    public string OperatorForCallTypeID { get; set; }
    public string OperatorForStatusID { get; set; }
}

public UpdateReportParameters(AdHocCallReportViewModel rvm)
{
    var type = rvm.GetType();
    foreach (var f in type.GetFields().Where(f => f.IsPublic))
    {
        Console.WriteLine(f.Name);
        Console.WriteLine(f.GetValue(rvm).ToString());
    }
}  

When stepping through the code, it skips over the foreach loop because GetFields returns zero items.

like image 850
Mike Roosa Avatar asked Jan 13 '10 16:01

Mike Roosa


3 Answers

You haven't got public fields. They are properties. So try type.GetProperties() instead.

like image 126
Wim Avatar answered Nov 08 '22 21:11

Wim


You are trying to get fields, you should try to call GetProperties()

like image 8
Restuta Avatar answered Nov 08 '22 19:11

Restuta


Pass BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public to get all instance fields.

On second thought, I'm seeing that you are explicitly filtering for public fields. The class does not have any public fields. The fields that are automatically generated by the compiler as the backing store for the properties are private.

like image 2
mmx Avatar answered Nov 08 '22 20:11

mmx