0

Say I have a class with a list like:

static class Accounts
{
   public static List<Account> Items;
   ...
}

I there a way to make it foreach enabled so that I can do foreach without referencing the Items list like:

foreach(Account account in Accounts) ?

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
xnp
  • 51
  • 2
  • 6

2 Answers2

2

No. Per section 10.1.1.3 of the C# 5.0 spec, static classes can't implement interfaces.

A static class declaration is subject to the following restrictions:

...

  • A static class may not include a class-base specification (§10.1.4) and cannot explicitly specify a base class or a list of implemented interfaces. A static class implicitly inherits from type object.

...

And as such, there's no way to implement IEnumerable, which is how foreach works.

I explored options making use of the fact that foreach will look do a member lookup or GetEnumerator if no interfaces are found, but that also doesn't work, because the expr argument that foreach is expecting does not support a type-name, unfortunately.

The best alternative would be to make it not static, and follow a singleton pattern instead. That is, have a static property that is the only allowable instance of the class. But that won't clear away the need to read a property, so it won't really get you anything anyway.

If you're just looking to obscure the implementation (good call), you could make the property of type IEnumerable<Account>, then set it equal (wherever you do that) to a new List<Account>. Then you aren't allowing, by contract, other classes to modify the list, and you aren't coupling them to the implementation. Those are the main advantages of implementing IEnumerable for something like this, anyway. So that should suffice.

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
0

Why not just use the list?

foreach (Account account in Accounts.Items)

If you want to implement this, you will need to inherit the IEnumerable interface and implement it's behavior.

In my opinion, doing so would be more confusing than just using the list directly.

Cyral
  • 13,999
  • 6
  • 50
  • 90