Mike Roosa
Mike Roosa

Reputation: 4802

Why does GetFields() not return anything?

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.

Upvotes: 7

Views: 12040

Answers (3)

Restuta
Restuta

Reputation: 5903

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

Upvotes: 9

Wim
Wim

Reputation: 12082

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

Upvotes: 31

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422046

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.

Upvotes: 2

Related Questions