Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metaprograming in C# : Automatic ToString Method

I have some classes which only serve to contain data. For example

public class EntityAdresse : IEntityADRESSE
{
    public string Name1 { get; set; }
    public string Strasse { get; set; }
    public string Plz { get; set; }
    public string Ort { get; set; }
    public string NatelD { get; set; }
    public string Mail { get; set; }
    public int Id_anrede { get; set; }
    public string Telefon { get; set; }
    public int Id_adr { get; set; }
    public int Cis_adr { get; set; }
}

This represents a address. Like I said, it only contains data. No Methods (I know the interface doesn't make sense here...)

Now I need to implement ToString for all this Entity-Classes and there are a lot of them.

My question is: Is there a metaprograming feature in C# which generates this tostring methods automaticaly? I don't want to write boiler plate code for every which of these classes.

Alternatively I could also write a perl or python script to generate the code. But I prefer doing it in C# directly.

like image 312
Luke Avatar asked Mar 06 '13 10:03

Luke


1 Answers

Generally, you need to obtain all property values of your class and combine them into a single string. This can be done using the following approach:

public override string ToString() 
{
    PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(this);
    StringBuilder builder = new StringBuilder();
    foreach(PropertyDescriptor pd in coll)
    {
        builder.Append(string.Format("{0} : {1}", pd.Name , pd.GetValue(this).ToString()));
    }
    return builder.ToString();
}
like image 115
platon Avatar answered Nov 15 '22 20:11

platon