Search code examples
c#wpfdelegatesconvertersivalueconverter

ivalueconverter vs system.converter vs delegate


I'm implementing a ConvertingCollection, which aims to provide a collection of converted items (B), given a live collection of original items (A). The Collection B would reflect any change occurring in Collection A. The target is to use it in MVVM as a collection of ViewModels given a collection of Models, but I believe that it could be used in many different contexts.

This class requires the user to provide a way to convert objects from a type A to a type B. I can find several ways to proceed, but I don't know enough about their differences to decide what is the best approach :

  • I could ask for an IValueConverter, which seems to be WPF-related. Now, nothing prevents to use it elsewhere, but it might be confusing. Although my class is first intended to be used in a WPF context, it is generic enough to apply to many other contexts. In addition, the IValueConverter converts from object to object, which means casting downstream, and no crash at build time.

  • I could opt for a System.Converter. This allows the usage of async and, even more pleasant, I can ask for specific types. Plus, this is not WPF-related in people's mind, as far as I know.

  • Finally, I could just go with a delegate doing TypeIn => TypeOut. No class to be instanciated, strongly typed, and the user could use any of IValueConverter, Converter or custom function to implement the delegate.

Now, I have no idea why the Converterand IValueConverterexist when everything could be handled with just delegates. So I guess I'm missing something there.

Can anyone please help ? Thanks in advance, Best regards


Solution

  • The best approach according to me:

    • Let the user decide whether to use IValueConverter or Converter by implementing a class that offers both possibilities.
    • The lambda is out of scope because a lambda expression is what is used on the user side to easily provide a delegate implementation. This means that a ConvertingCollection would expect a delegate as parameter, which is what a Converter already is.
    • Finally, the idea to use an implicit conversion is not kept because :
      • It forces the user to provide a conversion that could apply anywhere and not only in the sole context of the usage of ConvertingCollection, which may be problematic sometimes
      • In case an implicit conversion applies, is is easy to use it in a lambda expression
      • It makes the implementation of the ConvertingCollection more complex (check if an implicit conversion exists between the 2 types A and B), and I'm too lazy for this. Ok, that may be the first reason, but the other two are still valid. :)

    I hope this helps.