AutoPropertiesToString helper method

I needed in ToString() method for a class to log auto-properties.  Below are two methods that I used

/// <summary>

///

/// </summary>

/// <param name=”obj”></param>

/// <param name=”declaredOnly”></param>

/// <returns></returns>

/// <remarks> Created to log  DeclaredOnly in the current class using GetType().GetProperties(), for full object dump other methods may be more appropriate

/// See  http://stackoverflow.com/questions/4023462/how-do-i-automatically-display-all-properties-of-a-class-and-their-values-in-a-s

/// and  http://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object?lq=1

///  </remarks>

public static string AutoPropertiesToString( object obj, bool printNulls=false, bool declaredOnly=true)

{

BindingFlags flags = BindingFlags .Public |  BindingFlags.Instance;

if (declaredOnly) flags |= BindingFlags.DeclaredOnly;

var propertyInfos = obj.GetType().GetProperties(flags);

var sb = new StringBuilder();

foreach ( var info in propertyInfos)

{

if (info.IsAutoProperty())

{

var val = info.GetValue(obj, null);

if (printNulls == false && val == null)

continue;

var value = val ?? “(null)”;

sb.AppendLine(info.Name + “: ” + value);

}

}
return sb.ToString();

}
/// <summary>

/// It’s not fool proof, quite brittle

/// </summary>

/// <param name=”info”></param>

/// <returns></returns>

/// <remarks> from http://stackoverflow.com/questions/2210309/how-to-find-out-if-a-property-is-an-auto-implemented-property-with-reflection </remarks>

public static bool IsAutoProperty( this PropertyInfo info)

{

bool mightBe = info.GetGetMethod().GetCustomAttributes(typeof (CompilerGeneratedAttribute ),true ).Any();

if (!mightBe)

{

return false;

}

if (info.DeclaringType == null)

return false;

bool maybe = info.DeclaringType

.GetFields( BindingFlags.NonPublic | BindingFlags.Instance)

.Where(f => f.Name.Contains(info.Name))

.Where(f => f.Name.Contains( “BackingField”))

.Any(f => f.GetCustomAttributes(typeof (CompilerGeneratedAttribute ),true ).Any());
return maybe;

}

Advertisements

#net, #auto-properties, #tostring