I have two extension methods that are very similar. I'd like to remove the code duplicates with «the hole in the middle» pattern or the like, but can't really get it to work.
The code looks like so:
public static String GetPublicPropertiesAsString( this Object @this )
{
return @this.GetType().GetProperties()
.Select( propertyInfo =>
{
var propertyValue = propertyInfo.GetValue( obj: @this,
invokeAttr: BindingFlags.Public,
binder: null,
index: null,
culture: null );
var propertyValueAsString = propertyValue != null ? propertyValue.ToString().RemoveAll( "00:00:00" ) : "[null]";
return "{0}: {1}".FormatWith( propertyInfo.Name, propertyValueAsString );
} ).JoinAsString( Environment.NewLine );
}
public static String GetFieldsAsString( this Object @this )
{
return @this.GetType().GetFields()
.Select( fieldInfo =>
{
var fieldValue = fieldInfo.GetValue( @this );
var fieldValueAsString = fieldValue != null ? fieldValue.ToString().RemoveAll( "00:00:00" ) : "[null]";
return "{0}: {1}".FormatWith( fieldInfo.Name, fieldValueAsString );
} ).JoinAsString( Environment.NewLine );
}
Could the repetitive code above be refactored away?
Note: JoinAsString
, RemoveAll
, and FormatWith
are my own extension methods.