Click here to Skip to main content
15,888,233 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

1.You should overwrite the method ToString() in your EmployeeInfo class:
C#
public class EmployeeInfo
    {
        public string ename;
        public int eid;
        
        public override string ToString()
        {
            return string.Format("ename = \"{0}\" , eid = {1}",
                this.ename,
                this.eid);
        }
    }

2.You should refine/simplify the code from Button1_Click like this:
C#
protected void Button1_Click(object sender, EventArgs e)
    {
        EmployeeInfo obj = new EmployeeInfo { ename= "abc", eid = 123 };
        Response.Write(obj.ToString()); 
    }
 
Share this answer
 
Comments
Mohan_J 29-Aug-14 1:36am    
Without using string.Format, how to achieve this As I am using 100s of properites in a class and more manual work needed(adding property names) for this. Any simple way with good performnce.
Raul Iloc 29-Aug-14 2:01am    
Other solution, and the recommended solution for web communication, is to use JSON format, but this format is a little different that your format. See details on the next links:
http://weblogs.asp.net/scottgu/tip-trick-building-a-tojson-extension-method-using-net-3-5
http://dotnet.dzone.com/articles/converting-c-object-json
Mohan_J 1-Sep-14 0:43am    
thanks for your great answer. it works for me. ;)
Raul Iloc 1-Sep-14 1:05am    
Welcome, I am glad that I could help you!
Manual work is simple, you can use StringBuilder.Append if string.format would get too long.

Also, you could try to implement ISerializable interface (I'm not sure of the exact format of the output you would get, but you would definitely get a string with all the properties.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900