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 Converter
and IValueConverter
exist 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
The best approach according to me:
IValueConverter
or Converter
by implementing a class that offers both possibilities.ConvertingCollection
would expect a delegate as parameter, which is what a Converter
already is.ConvertingCollection
, which may be problematic sometimesConvertingCollection
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.