Sign in to follow this  
NisseBosseLasse

[C#] foreach

Recommended Posts

In some of my classes I would like to have the ability to iterate through the items using a foreach-loop. As long as I'm not using any static members, everything works fine:
public class Inventory
{
	// ..lots of non-static methods...

	public IEnumerator GetEnumerator ()
	{
		return m_items.GetEnumerator ();
	}

	// Private array holding a bunch of Items-classes
	private ArrayList m_items = new ArrayList ();
}

I can then use my inventory-class this way:
foreach (Item item in Player.Inventory)
{
	// Do something with the item
}

But now I have a problem using GetEnumerator on a class with static members. The class looks something like this:
public class Players	
{
	public static void Add (Player player)
	{
		m_players.Add (player);
	}

	// ...more static methods...

	public static IEnumerator GetEnumerator ()
	{
		return m_players.GetEnumerator ();
	}

	// Hold a bunch of Player-classes
	private static ArrayList m_players = new ArrayList ();
}

The error message is 'Players' denotes a 'class' where a 'variable' was expected. Do I have to use a delegate instead, or is there a way to fix this?

Share this post


Link to post
Share on other sites
ToohrVyk    1595
To best of my knowledge, you can't use foreach on static classes (which is another argument in disfavour of global state). If you'd rather keep your static class than avoid the additional work of working around global state limitations, you can always:


public class PlayersView
{
public IEnumerator GetEnumerator ()
{
return Players.GetEnumerator ();
}
}

foreach (Player player in new PlayersView())
{
// frobnicate
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Saughmraat
public class Players
{
public static void Add (Player player)
{
///

The class name is "Players" and the argument type is "Player".

Was it intentional?


Yes - the Players class keeps track of Player-classes.

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
To best of my knowledge, you can't use foreach on static classes (which is another argument in disfavour of global state). If you'd rather keep your static class than avoid the additional work of working around global state limitations, you can always:

*** Source Snippet Removed ***


Thanks, that worked!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this