views:

47

answers:

2

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!

+2  A: 

I'd suggest you to convert the collection using:

var viewModelCollection = new ObservableCollection<ViewModel>(modelCollection.Cast<ViewModel>());

If you like exstensions you could define something like (to avoid the new in the previous code):

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
{
   return new ObservableCollection<T>(coll);
}

Or maybe, to do everything in one shot:

public static ObservableCollection<TNew> CastObservable<TNew,TOld>(this ObservableCollection<TOld> originalColl)
{
   return new ObservableCollection<TNew>(originalColl.Cast<TNew>());
}

Obviously all the previous codes, will work if you have defined the snippet #2

digEmAll
@digEmAll... Awesome! Thanks!
Vyas Bharghava
A: 

Your first code snippet should work as a udc on the observablecollection class.

Ben Robinson
I guess ObservableCollection is not his own code, but maybe this one --> http://msdn.microsoft.com/en-us/library/ms668604%28v=VS.95%29.aspx
digEmAll