Reputation: 103627
I have an interface with:
IList<int> CategoryIDs {get;set;}
Then a class that inherits this interface:
public IList<int> CategoryIDs
{
get {} // this part works
set { _categoryIDs = value; // error!
}
The set part of the accessor reports an error:
cannot implicity convert type
IList<int>
toList<int>
.
What should I do? confused.
Upvotes: 0
Views: 3393
Reputation: 564691
Two things:
1) It's usually a bad idea to put a setter on an IList<T>
member. You typically want people to work on your existing list, but not replace it completely. This would look like:
public interface IMyInterface {
IList<int> CategoryIDs {get;} // Only put get
}
public class MyClass : IMyInterface
{
List<int> categoryIDs;
public IList<int> CategoryIDs
{
get { return this.categoryIDs; }
}
}
2) If you do need to do that, you'll have to either cast the IList<T>
to a List<T>
in order to set it, or make a copy.
public interface IMyInterface {
IList<int> CategoryIDs {get;set;}
}
public class MyClass : IMyInterface
{
List<int> categoryIDs;
public IList<int> CategoryIDs
{
get { return this.categoryIDs; }
set
{
List<int> asList = value as List<int>;
if (asList != null)
this.categoryIDs = asList;
else
this.categoryIDs = new List<int>(value); // Copy values across into new list!
}
}
}
Either way, this approach is a bit "clunky" feeling.
Upvotes: 2
Reputation: 51186
You can instantiate and assign a List just fine with a minor tweak:
private IList<int> _categoryIDs; // use IList instead of List
public IList<int> CategoryIDs
{
get { return _categoryIDs; }
set { _categoryIDs = value; }
}
Upvotes: 1
Reputation: 101605
Apparently, your field _categoryIDs
is declared as List<T>
, while your property is IList<T>
(or even IList
, it's hard to say with broken source code formatting in the question). IList<T>
(and IList
) is an interface; List<T>
is a class implementing that interface. Because of that, you can assign List
reference to variable of type IList
, but not vice versa.
Upvotes: 0
Reputation: 124732
IList is an interface, List is a concrete class. List may implement IList, but other classes may as well, so you cannot assign an IList to a List without a cast. Try something like this instead:
private IList<int> _list = new List();
public IList<int> List
{
get { return _list; }
set { _list = value; }
}
Of course, you should not be writing code in your class that assumes that List or _list is actually a list, you should be treating it generically as an IList.
Upvotes: 2