Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

(Dynamically) Implement ToString() as a Lambda Function

0.00/5 (No votes)
16 Jun 2016 2  
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();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here