I have a simple lookup list that I will use to populate a dropdown in Silverlight. In this example I’m using US States.
I’m trying to figure out if its better to return a static list or use the yield keyword. Of the following two pieces of code, which is the preferred and why?
Version 1: Using yield 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 the 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;
}
}
The question you need to ask yourself is : “do I want the code that calls
GetNamesto be able to modify the list ?”IList, implicitly saying : “read-write”IEnumerable, implicitly saying : “read-only”Anyway, I think you should put the state names in a resource file, rather than hard-coding them (even though that list is unlikely to change in the short term…)
Here is what I would do :
This way you don’t directly expose the list to the “outside world”