Is it better to give return search lists or preload a static list in C #?
I have a simple lookup list that I will use to populate a dropdown in Silverlight. In this example, I am using US.
I am trying to figure out if it is better to return a static list or use yield . Of the next two pieces of code, which is preferred and why?
Version 1: Using Return Return
public class States
{
public static IEnumerable<string> GetNames()
{
yield return "Alabama";
yield return "Alaska";
yield return "Arizona";
yield return "Arkansas";
yield return "California";
yield return "Others ...";
}
}
Version 2: Return a list
public class States
{
private static readonly IList<string> _names;
static States()
{
_names = new List<string>() {"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Others ..." };
}
public static IList<string> GetNames()
{
return _names;
}
}
source to share
The question you need to ask yourself is "I want the caller GetNames
to be able to modify the list?"
- If so, return a
IList
, implicitly saying "read-write" - If the answer is no, return
IEnumerable
, implicitly, "read-only"
Anyway, I think you should put the state names in the resource file, not hardcode them (although this list is unlikely to change in the short term ...)
Here's what I would do:
public static IEnummerable<string> GetNames()
{
foreach(string name in _names) yield return name;
}
So you cannot directly show the list to the "outside world"
source to share
This might help explain why you should go with V1 http://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/