Static Reflection

I am having a list of Person as follows:

  1. var obj = new List<Person> { new Person { ID = 1, Name = "Arunava" }, new Person { ID = 2, Name ="Bubu" } };  
My goal is to get the output as :

Name=Arunava ID=1
Name=Bubu ID=2

in the console. Let's see how we can achieve that without using reflection. I used Linq.Expressions to achieve this.

Simple method to add in your model class, called GetPropertyName and also change the ToString method. My model class is as follows:

  1. public class Person  
  2. {  
  3.     public string Name { getset; }  
  4.     public int ID { getset; }  
  5.     public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)  
  6.     {  
  7.         var me = propertyLambda.Body as MemberExpression;  
  8.         return me.Member.Name;  
  9.     }  
  10.     public override string ToString()  
  11.     {  
  12.         return String.Format("{0}={1} {2}={3}", GetPropertyName(() => Name), Name,GetPropertyName(()=>ID),ID);  
  13.     }  
  14. }  
We are ready to get the expected result. See my console app:
  1. var obj = new List<Person> { new Person { ID = 1, Name = "Arunava" }, new Person { ID = 2, Name ="Bubu" } };  
  2. obj.ForEach(data=> Console.WriteLine(data));  
Try this now. Hope this helps.