Why am I getting error: "cannot implicitly convert type System.Collections.Generic.List"

Debbie picture Debbie · May 5, 2013 · Viewed 8.2k times · Source

I have the following sealed class. I'm trying to return the list as a ReadOnlyCollection. Tried a couple of things but I'm not getting the hang of this. So how do I return or cast the list to the readonly collection?

    public sealed class UserValues
    {
        private readonly List<UserValue> _Values = new List<UserValue>();

        public ReadOnlyCollection<UserValues> Values
        {
            get
            {
                return _Values;
            }
        }
    }

Answer

Gjeltema picture Gjeltema · May 5, 2013

Try:

return new ReadOnlyCollection<UserValue>(_Values);

Edit:

Given what you've said to Jon, your code doesn't make sense. Your get is referencing a type of List<UserValue>, but you're wanting to convert it to a type of ReadOnlyCollection<UserValues>, which cant be done - that's 2 collections of 2 different types.

We'll need more information to help you answer this question. Are you wanting your UserValues class to return a collection of UserValues types, or a collection of UserValue types? Your code implies UserValue, but your follow on comments state UserValues. Are you sure your supervisor didn't make a typo?

If not, you'll need some internal collection like so:

private readonly List<UserValues> _MoreValues = new List<UserValues>();

And then return that, in the syntax that I (or others who have answered - all the answers given are valid for converting a List to a ReadOnlyCollection) have shown.

Note that my code compiles targeting .Net 3.5, presuming that the types are compatible (meaning ReadOnlyCollection<UserValue> wraps List<UserValue>, or both are UserValues).