Reputation: 10153
I have an external method which returns List<IPAddress>
I write in my class other method which is a wrapper for that. But I was told to not return List<>
,but IList
or ICollection
.
For now what I have :
MyClass obj = new MyClass();
List<IPAddress> addr = obj.GetAddr();//GetAddr() now return `List`,but should be changed to return ILIst or ICollection
What should I do - casting?
Upd I did what you said and get an errr "can`t implicitly convert Ilst to List (It is .net 4.5)
Upvotes: 1
Views: 632
Reputation: 68750
What he/she probably meant is: return the list as an IList<T>
or ICollection<T>
.
In order to do that, simply change your method's signature and return the list as you normally would:
public ICollection<T> Method(){
MyClass obj = new MyClass();
List<IPAddress> addr = obj.GetAddr();
return addr;
}
This is to avoid binding your client's to a concrete List<T>
implementation.
By returning something more abstract, like an ICollection<T>
, or even an IEnumerable<T>
, you won't run into any problems if you later decide to use a HashSet<T>
instead of a List<T>
internally. The signature and the client's code will remain the same.
Upvotes: 2
Reputation: 12815
If obj.GetAddr()
returns IList<IPAddress>
, ICollection<IPAddress>
, or IEnumerable<IPAddress>
, all you need to do is add .ToList()
to the end of your assignment:
List<IPAddress> addr = obj.GetAddr().ToList();
Or, you can follow the current convention of not explicitly typing your variables, and just do the following:
var addr = obj.GetAddr();
This will then allow you to maintain your addr
variable as whatever return type your GetAddr()
method returns. You will still have access to all the properties of that return type.
Upvotes: 0
Reputation: 1825
You can change the method return type to IList<IPAddress>
or IEnumerable<IPAddress>
like:
public IList<IPAddress> GetAddress()
{
return new List<IPAddress>(); //replace with your code to return list
}
public IEnumerable<IPAddress> GetAddress()
{
return new List<IPAddress>(); //replace with your code to return list
}
Upvotes: 1
Reputation: 203812
Just change the return value of the method. Since List
is implicitly convertible to both interfaces, there is no need for any cast.
Upvotes: 0