Keith Barrows
Keith Barrows

Reputation: 25308

typeof(T).GetFields() returning zero length array

I am trying to get a list of fields from an object. I have confirmed that the object is being passed in with this call:

var account = SymitarInquiryDeserializer.Deserialize<SymitarAccount>(jString);

When I try to get the fields it returns a zero length array and I can't see what I am doing wrong here.

My object definition:

public class SymitarAccount
{
    public int PositionalIndex { get; set; }
    /// <summary>IQ: ~JID: Account/Share Id (format: 0000)</summary>
    [SymitarInquiryDataFormat("ID")]
    public int Id { get; set; }
    /// <summary>IQ: ~JCLOSEDATE: Account/Share Closed Date where 00000000 is still open (format: YYYYMMDD)</summary>
    [SymitarInquiryDataFormat("CLOSEDATE")]
    public DateTime? CloseDate { get; set; }
    public bool IsClosed { get; set; }
    /// <summary>IQ: ~JDIVTYPE: Account/Share Div Type (format: 0)</summary>
    [SymitarInquiryDataFormat("DIVTYPE")]
    public int DivType { get; set; }
    /// <summary>IQ: ~JBALANCE: Account/Share Balance (format: 0.00)</summary>
    [SymitarInquiryDataFormat("BALANCE")]
    public decimal Balance { get; set; }
    /// <summary>IQ: ~JAVAILABLEBALANCE: Account/Share Avaialable Balance (format: 0.00)</summary>
    [SymitarInquiryDataFormat("AVAILABLEBALANCE")]
    public decimal AvailableBalance { get; set; }
}

My method to get fields:

public static T Deserialize<T>(string str) where T : new()
{
    var result = new T();
    ....
    // Get fields of type T
    var fields = typeof(T).GetFields();    //BindingFlags.Public | BindingFlags.Instance);
    foreach (var field in fields)
    {
        ....
    }
    ....
}

Any ideas?

Upvotes: 0

Views: 1562

Answers (3)

Paul Bright
Paul Bright

Reputation: 53

public void FindFieldNames<T>(List<T> data)
{
      foreach (var prop in data.GetType().GetProperties())
      {           
           Console.WriteLine($@"{prop.Name}");                
      }    
}

Upvotes: 0

Sean
Sean

Reputation: 62492

GetFields returns public variables. What you're after is the property names which you can get by calling GetProperties

Upvotes: 2

Kevin Gosse
Kevin Gosse

Reputation: 39007

Those are not fields but properties. Use GetProperties instead:

var properties = typeof(T).GetProperties();

Upvotes: 10

Related Questions