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

Arunava BhattacharjeePosted Aug 29, 2014, 7:08 AM
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.