Monday, December 11, 2006

Custom object and ToString()

It is known that in the C # any object can be shown in the form of string by the method ToString () but what to do if you need to make such an operation with custom object?
That is one solution :

public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private DateTime birthday ;
public DateTime Birthday
{
get { return birthday ; }
set { birthday = value; }
}


//Constructor
public Customer()
{
this.id = 5;
this.name = "John Smith";
this.birthday = new DateTime(1945, 10, 12);

Console.WriteLine(this.ToString());
}



To continue press "read more"....




public override string ToString()
{
StringBuilder builder = new StringBuilder();

Type type = this.GetType();
PropertyInfo[] propertiesInfo =
type.GetProperties();
foreach (PropertyInfo property in propertiesInfo)
{
builder.AppendFormat("{0} = {1} \n",
property.Name,
property.GetValue(this, null));
}

return builder.ToString();
}


Output:



kick it on DotNetKicks.com

No comments: