Click here to Skip to main content
15,891,633 members
Articles / Programming Languages / C#
Tip/Trick

(Dynamically) Implement ToString() as a Lambda Function

Rate me:
Please Sign up or sign in to vote.
4.60/5 (10 votes)
16 Jun 2016CPOL 10.8K   5   1
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.

C#
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.

C#
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:

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Wischner Ltd
United Kingdom United Kingdom
Writing code since 1982 and still enjoying it.

Comments and Discussions

 
PraiseNice simple pattern Pin
aeastham17-Jun-16 2:05
aeastham17-Jun-16 2:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.