Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Offhand, I can think of two ways to do it. However, since it must be <code>IEnumerable&lt;string&gt;</code> it can't be a static class because static classes can't implement interfaces. Nor can static methods implement interface methods.</p> <p>The first way uses constants and an enumerator that just returns them in order:</p> <pre><code>public class Features: IEnumerable&lt;string&gt; { public const string Favorite = "blue background"; public const string Nice = "animation"; public IEnumerator&lt;string&gt; GetEnumerator() { yield return Favorite; yield return Nice; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } </code></pre> <p>The second way stores the values in an array and uses an <code>enum</code> for the indexes. The enumerator just returns the enumerator for the array. Again, this is not static because of the enumerator, and also because indexers can't be static.</p> <pre><code>public enum FeaturesIndex { Favorite = 0, Nice = 1 } public class Features2 : IEnumerable&lt;string&gt; { private static readonly string[] _features = new string[] { "blue background", "animation" }; public string this [FeaturesIndex ix] { get { return _features[(int) ix]; } } public IEnumerator&lt;string&gt; GetEnumerator() { return ((IEnumerable&lt;string&gt;) _features).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } </code></pre> <p>A third possibility, as pointed out by others, is using a dictionary and either an enumeration or defined constants as keys. It's an interesting approach, the only potential drawback being that you can't guarantee the order in which keys will be returned when you enumerate the collection. If that's a problem, you could have your enumerator sort the sequence before returning.</p> <p>Any way you look at it, there are tradeoffs. Both of my solutions require manual synchronization of keys and values. In the first, you have to make sure that the enumerator retures all of the values. In the second, you have to ensure that your <code>enum</code> matches the array.</p> <p>Pick your poison.</p> <p>It also depends on how you're going to use the thing. My first solution has the benefit of simplicity and would probably be quite acceptable if it's a write-once, use-forever kind of thing. The second option has the benefit of using an indexer, which is more commonly associated with collections.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload