Use reflections to find property info in c#

Default annotations and user-defined anotations can be extracted using reflections. These act like meta-data and can simplify operations such as UI.

Let’s create a class and decorate it’s proeprties. Note that variables cannot be annotated.

public class UserClass
{
  [System.ComponentModel.DisplayName("User name")]
  public string Name { get; set; }
  [System.ComponentModel.DisplayName("Age (in years)")]
  public int Age { get; set; }
  public string Url { get; set; }
}

In next step, we will use reflections to get the annotation values.

static void Main(string[] args) { 
  var obj = new UserClass() {
    Name = "Wordpress", 
    Age = 10, 
    Url = "http://www.wordpress.com" 
  };
  var datatype = typeof(UserClass);
  var propArray = datatype.GetProperties(); 
  foreach (PropertyInfo prop in propArray) {
    var propertyName = prop.Name;
    var propertyValue = prop.GetValue(obj);
    var propertyType = prop.PropertyType;
    string displayName = propertyName;
    if (prop.GetCustomAttribute(typeof(DisplayNameAttribute)) is DisplayNameAttribute displayAttribute) 
      displayName = displayAttribute.DisplayName; 
    var isDerivedProperty = !(prop.DeclaringType == datatype);
    System.Console.WriteLine($"{displayName}, {propertyValue}");
    if(isDerivedProperty)if(isDerivedProperty) 
      System.Console.WriteLine($"{displayName} property is defined in based class");
  }
}

The output should look like:

User name, WordPress
Age (in years), 10
Url, http://www.wordpress.com

Github gist: Here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s