Type casting Collections using Conversion Operators

Posted by Vyas Bharghava on Stack Overflow See other posts from Stack Overflow or by Vyas Bharghava
Published on 2010-06-15T07:22:10Z Indexed on 2010/06/15 7:22 UTC
Read the original article Hit count: 182

Filed under:
|
|
|

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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about operators