The below code gives me User-defined conversion must convert to or from enclosing type, while snippet #2 doesn’t… It seems that a user-defined conversion routine must convert to or from the class that contains the routine.
What are my alternatives? Explicit operator as extension method? Anything else?
public static explicit operator ObservableCollection<ViewModel>(ObservableCollection<Model> modelCollection)
{
var viewModelCollection = new ObservableCollection<ViewModel>();
foreach (var model in modelCollection)
{
viewModelCollection.Add(new ViewModel() { Model = model });
}
return viewModelCollection;
}
Snippet #2
public static explicit operator ViewModel(Model model)
{
return new ViewModel() {Model = model};
}
Thanks in advance!
I’d suggest you to convert the collection using:
If you like exstensions you could define something like (to avoid the new in the previous code):
Or maybe, to do everything in one shot:
Obviously all the previous codes, will work if you have defined the snippet #2