hi, In C#, I need to print a class field or property name with value without using reflection or string.join method.
For eg.
Code
protected void Button1_Click(object sender, EventArgs e)Code
{ ListEmployeeInfo> obj = new ListEmployeeInfo>();Code
obj.Add(new EmployeeInfo { eid = 123 });Code
obj.Add(new EmployeeInfo { ename = "abc" });Code
Response.Write(obj.ToString()); // output must be => ename ="abc" , eid = 123 }Code
public class EmployeeInfoCode
{ public string ename;Code
public int eid;Code
}It need to be resulted as follows automatically with property name and value :
Code
ename ="abc" , eid = 123It need to be resulted with good performance and simple way.


Arunava BhattacharjeeRank #635 · 3.8K reputationPosted Aug 29, 2014, 3:08 AM EDT
Interesting.I tried this and liked it too.I am also posting it as a blog for wide range of audience. I used System.Linq.Expressions. It's tested and its working fine. Please check the performance and if it's ok please use it as I don't think it uses Reflection anywhere.
Simple method to add in your model class, called GetPropertyName and also change the ToString method. My model class is as follows:
public class Person
{
public string Name { get; set; }
public int ID { get; set; }
public string GetPropertyName( Expression<Func> propertyLambda)
{
var me = propertyLambda.Body as MemberExpression;
return me.Member.Name;
}
public override string ToString()
{
return String.Format("{0}={1} {2}={3}", GetPropertyName(() => Name), Name,GetPropertyName(()=>ID),ID);
}
}
We are ready to get the expected result. See my console app:
var obj = new List<Person> { new Person { ID = 1, Name = "Arunava" }, new Person { ID = 2, Name = "Bubu" } };
obj.ForEach(data=> Console.WriteLine(data));
Try this now. Hope this helps.