Look into following line of code:
public string[] GetStringList(params object[] values)
{
List<string> _stringList = new List<string>();
foreach (object value in values)
{
_stringList.Add(Convert.ToString(value));
//Do something
}
//Why this invalid?
return _stringList;
//Why do required to convert list collection in array
return _stringList.ToArray();
}
Since List and Array both are colletions then why should I need to convert List into Array?
Since List and Array both are collections then why should I need to convert List into Array?
Yes, they are both collections, but your method signature specifies exactly what type of collection it returns, and that's why you have to return exactly that one collection type.
You can change your method declaration to return collection of strings using one of collection interfaces:
public IEnumerable<string> GetStringList(params object[] values)
or
public ICollection<string> GetStringList(params object[] values)
It will allow you to return both List<string>
and string[]
, because they both implement the interface. You could also return HashSet<string>
or even Queue<string>
(for IEnumerable<string>
version only. Or write your own class, implement the interface you're interested in and return it within your method.
But as soon as you declare the method using string[]
, you have to return something that is an array of string
s, and List<string>
does not fulfill that requirement.
OFT advice
You can make your code a little faster passing values.Length
as List<string>
constructor parameter:
List<string> _stringList = new List<string>(values.Length);
it will initialize list internal storage with necessary amount of memory and let you add all your items without reallocating any memory.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments