Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
            }
        }
    }
like image 977
Debbie Avatar asked May 05 '13 20:05

Debbie


2 Answers

You're getting the compile-time error because a List<UserValue> is not a ReadOnlyCollection<UserValue>, nor is it implicitly convertible to that. (I assume you meant ReadOnlyCollection<UserValue> instead of ReadOnlyCollection<UserValues> by the way?)

It's probably simplest to use List<T>.AsReadOnly - but you might as well only create it once:

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

    public UserValues()
    {
        valuesView = values.AsReadOnly();
    }

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

The ReadOnlyCollection<T> really is just a view - so changes to the underlying collection will be visible through the view.

like image 139
Jon Skeet Avatar answered Oct 07 '22 20:10

Jon Skeet


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).

like image 30
Gjeltema Avatar answered Oct 07 '22 20:10

Gjeltema