/// <summary>
/// This does NOT go into sub objects, only the top level object
/// i.e. if you have a class with a string field, it will trim that string field value
/// but not trim any string fields on sub-objects inside the containing class
/// </summary>
/// <param name="currentObject"></param>
public static void SafeTrimAllStringFields(this object currentObject)
{
if (currentObject == null)
{
return;
}
var type = currentObject.GetType();
var stringFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(f => f.FieldType == typeof(string));
foreach (var field in stringFields)
{
var value = (string)field.GetValue(currentObject);
if (value != null)
{
field.SetValue(currentObject, value.SafeTrim());
}
}
}
}
public static string SafeTrim(this string value)
{
return value == null ? string.Empty : value.Trim();
}
Tag Archives: c#
Test base class thanks to Rob Connery
I saw this great testbase class in a Tekpub video. Thank goodness for tekpub videos. I wish everything that I purchased was that pragmatic.
public class TestBase { public static string GetCaller() { StackTrace stackTrace = new StackTrace(); return stackTrace.GetFrame(2).GetMethod().Name; } public void IsPending() { Console.WriteLine("{0} -- pending", GetCaller()); } public void Describes(string description) { Console.WriteLine("-----------------------"); Console.WriteLine(description); Console.WriteLine("-----------------------"); } }