public class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } ...... var emp1Address = new Address(); emp1Address.AddressLine1 = "Microsoft Corporation"; emp1Address.AddressLine2 = "One Microsoft Way"; emp1Address.City = "Redmond"; emp1Address.State = "WA"; emp1Address.Zip = "98052-6399";
Consider the class above, and then initialize it. Now at some point I want to record its status when an error occurs. I would like to get a string log as shown below.
string toLog = Helper.GetLogFor(emp1Address);
sting toLog should look something like this.
AddressLine1 = "Microsoft Corporation"; AddressLine2 = "One Microsoft Way"; City = "Redmond"; State = "WA"; Zip = "98052-6399";
And then I will write the line toLog .
How can I access all property names and object property values ββin the Helper.GetLogFor() method?
The solution I implemented: -
/// <summary> /// Creates a string of all property value pair in the provided object instance /// </summary> /// <param name="objectToGetStateOf"></param> /// <exception cref="ArgumentException"></exception> /// <returns></returns> public static string GetLogFor(object objectToGetStateOf) { if (objectToGetStateOf == null) { const string PARAMETER_NAME = "objectToGetStateOf"; throw new ArgumentException(string.Format("Parameter {0} cannot be null", PARAMETER_NAME), PARAMETER_NAME); } var builder = new StringBuilder(); foreach (var property in objectToGetStateOf.GetType().GetProperties()) { object value = property.GetValue(objectToGetStateOf, null); builder.Append(property.Name) .Append(" = ") .Append((value ?? "null")) .AppendLine(); } return builder.ToString(); }
IsmailS
source share