This class can be useful for when you want to override the Object.ToString
method on a type you don't have access to edit.
public class ToStringWrapper<T>
{
private readonly T _wrappedObject;
private readonly Func<T, string> _toStringFunction;
public T WrappedObject
{
get { return _wrappedObject; }
}
public ToStringWrapper(T wrappedObject, Func<T, string> toStringFunction)
{
this._wrappedObject = wrappedObject;
this._toStringFunction = toStringFunction;
}
public override string ToString()
{
return _toStringFunction(_wrappedObject);
}
}
Sample usage: Don't have access to edit the Person
type and you want the Name
property's value to be returned in the ToString
method.
public sealed class Person
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var person = new Person { Name = "TestName" };
Console.WriteLine(person);
var personWrapper = new ToStringWrapper<Person>(person, i => i.Name);
Console.WriteLine(personWrapper);
Console.ReadKey();
}
}
Output:
ConsoleApplication1.Person
TestName
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.