Dynamically enumerate properties from a class

//Let's have a class first- 
public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
}


using System;
using System.Collections.Generic;
using System.Reflection;

//In case of single object
-----------------------------
void EnumerateField<T>(T t)
{
    PropertyInfo[] props = typeof(T).GetProperties();
    foreach (PropertyInfo property in props)
    {
        string propertyName = property.Name.ToString();
        string propertyType = property.PropertyType.ToString();
        string propertyValue = property.GetValue(t).ToString();
    }
}

//Usage-
Student student = new Student() { StudentId = 100, StudentName = "Shindhu-100" };
EnumerateField(student);


//In case of list<T>
-----------------------------------
void EnumerateFields<T>(List<T> ListOfT)
{
    PropertyInfo[] props = typeof(T).GetProperties();
    foreach (var t in ListOfT)
    {
        foreach (PropertyInfo property in props)
        {
            string propertyName = property.Name.ToString();
            string propertyType = property.PropertyType.ToString();
            string propertyValue = property.GetValue(t).ToString();
        }
    }
}

//Usage-
List<Student> students = new List<Student>();
students.Add(new Student() { StudentId = 1, StudentName = "a" });
students.Add(new Student() { StudentId = 2, StudentName = "b" });
Student st = new Student() { StudentId = 100, StudentName = "Shindhu-100" };
students.Add(st);
EnumerateFields<Student>(students);
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