Simone Spagna
Simone Spagna

Reputation: 644

C# : propertyinfo always empty

i have an issue with c# reflection. The object I want to reflect is the following :

public partial class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
    }

    public decimal CustomerId { get; set; }

    public string AlexaAccessToken { get; set; }

    public string GoogleHomeAccessToken { get; set; }
}

The code I use to reflect is the following :

    Dictionary<string,string> GetReplacement(ApplicationUser applicationUser)
    { 

        Dictionary<string, string> toRet = new Dictionary<string, string>();

        PropertyInfo[] propertyInfos;
        propertyInfos = typeof(ApplicationUser).GetProperties(BindingFlags.Public);

        Array.Sort(propertyInfos,
            delegate (PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });


        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            toRet.Add(propertyInfo.Name,propertyInfo.GetValue(applicationUser).ToString());
        }

        return toRet;
    }

The problem is that the dictionary is always empty because propertyinfo is always empty. What is the problem? Thank you all in advance.

Upvotes: 2

Views: 654

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

There are two problems here:

  1. bind via BindingFlags.Public | BindingFlags.Instance
  2. check for null values: propertyInfo.GetValue(applicationUser)?.ToString() or Convert.ToString(propertyInfo.GetValue(applicationUser))

Upvotes: 3

Related Questions