Processes all properties on an object and resets them to the default value.
using System;
using System.Reflection;
public static class Extensions
{
/// <summary>
/// Processes all properties on an object
/// and resets them to the default value.
///
/// Loops through all the properties on any object,
/// resetting each property to its default value.
/// </summary>
/// <param name="obj">The target object.</param>
/// <typeparam name="T">The type parameter.</typeparam>
/// <example>
/// var cust = new Customer("A123");
/// cust.SetPropertiesToDefaultValues();
/// </example>
/// <remarks>https://visualstudiomagazine.com/articles/2016/05/27/processing-all-properties-object-dotnet.aspx</remarks>
public static void SetPropertiesToDefaultValues<T>(this T obj)
{
foreach (var prop in obj.GetType().GetProperties())
{
Type propType = prop.GetType();
if ((prop.PropertyType.Name == "String"))
{
prop.SetValue(obj, String.Empty);
}
else if (propType.GetTypeInfo().IsValueType)
{
prop.SetValue(obj, Activator.CreateInstance(propType));
}
else
{
prop.SetValue(obj, null);
}
}
}
}
//
// Usage
var cust = new Customer("A123");
cust.SetPropertiesToDefaultValues();