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;
    }
}

      

+2


source to share


4 answers


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"

+1


source


I think I would prefer a list for this. The only advantage that a method yield

can offer in List is to avoid having to store all the items in memory at once, but you will do that anyway.



+1


source


+1


source


Personally, I would prefer a List over an iterator, although I would also look at embedding a resource containing such a list (perhaps XML, possibly plain text) into your assembly and read that in your static constructor.

0


source







All Articles