I have two extension methods that are very similar. I would like to remove duplicate code using a “hole in the middle” or the like, but cannot make it work.
The code looks like this:
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 );
}
Can relay the repeating code above?
Note: JoinAsString, RemoveAlland FormatWith- my own extension methods.
source
share