65.9K
CodeProject is changing. Read more.
Home

(Dynamically) Implement ToString() as a Lambda Function

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (9 votes)

Jun 16, 2016

CPOL
viewsIcon

11148

How to (dynamically) implement ToString() as a Lambda function

Background

You’d like to manually populate a combo box with a collection of 3rd party objects. These objects do not have a display property to bind to, are sealed, and already use ToString() for another purpose.

The Code

The solution to this problem is to use generics and lambda function to dynamically wrap your class and add a custom function to it.

public class Stringable<T>
{
    private T _obj;
    private Func<T, string> _convertFn;
    public Stringable(T obj, Func<T, string> convertFn)
    {
        _obj = obj;
        _convertFn = convertFn;
    }
    public T GetObj() { return _obj; }
    public override string ToString() { return _convertFn(_obj); }
}

This class will allow you to wrap an object and use lambda function to dynamically implement ToString() from its’ properties.

Stringable<CustomerModel> customerItem = new Stringable<CustomerModel>(customer, c => c.Name);

You can now pass customerItem to your combo box. And, finally, when the user selects a combo box item, you can recall the original object like this:

CustomerModel selCustomer = (cbo.SelectedItem as Stringable<CustomerModel>).GetObj();