Reputation: 35
I have a class like this with a bunch of properties:
class ClassName
{
string Name {get; set;}
int Age {get; set;}
DateTime BirthDate {get; set;}
}
I would like to print the name of the property and it's value using the value's ToString() method and the Property's name like this:
ClassName cn = new ClassName() {Name = "Mark", Age = 428, BirthData = DateTime.Now}
cn.MethodToPrint();
// Output
// Name = Mark, Age = 428, BirthDate = 12/30/2010 09:20:23 PM
Reflection is perfectly okay, in fact I think it is probably required. I'd also be neat if it could somehow work on any class through some sort of inheritance. I'm using 4.0 if that matters.
Upvotes: 2
Views: 2347
Reputation: 37516
Like you mentioned, you can accomplish this with reflection. Make sure you're using System.Reflection
.
public void Print()
{
foreach (PropertyInfo prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
object value = prop.GetValue(this, new object[] { });
Console.WriteLine("{0} = {1}", prop.Name, value);
}
}
Upvotes: 2
Reputation: 4637
If you are only going to use this class, you can override the ToString method, like this:
public override string ToString()
{
return string.Format("Name = {1}, Age = {2}, BirthDate= {3}", Name, Age, BirthData.ToLongTimeString());
}
If you need to represent only that class, then this would be the solution. You can do something like
ClassName jhon = ....
Console.WriteLine(jhon);
Upvotes: 2
Reputation: 128377
What you want is typeof(ClassName).GetProperties()
. This will give you an array of PropertyInfo
objects, each of which has a Name
property as well as a GetValue
method.
Upvotes: 3