3

I am switching from Java to C# and I am wondering if this is possible? What I want to do is create a two dimensional array of the type Enum {north, south, east, west}. That way I can call map[1,2].north to find out if that cell on the map has a north wall or not.

Sorry for the crude code, I do not have access to my computer at the moment, so I am being a bit abstract.

2
  • Can a cell have more than one wall? Commented Aug 17, 2017 at 19:15
  • Since you're coming from Java, you might want to know that enums in C# are quite a bit weaker. Commented Aug 17, 2017 at 20:14

3 Answers 3

3

For the enum:

enum Dirs { North, South, East, West } 

Just declare an array as:

Dirs[,] dirs = new Dirs[10, 10]; 

If you need each cell to be able to have several walls, mark the enum with the [Flags] attribute and make the values to be powers of 2:

[Flags] enum Dirs { North = 1 << 0, South = 1 << 1, East = 1 << 2, West = 1 << 3 } 

Thus you'll be able to set, for instance:

dirs[1, 2] = Dirs.North | Dirs.East; 

And as @Scott Chamberlain mentioned in his comment - to check a direction you can do:

bool hasNorthWall = dirs[1, 2].HasFlag(Dirs.North); 
Sign up to request clarification or add additional context in comments.

6 Comments

The Flags attribute does not change the values of the enum members. If you use it, you need to explicitly set the values to be powers of 2, otherwise you'll end up with some undesired behavior.
To be complete, to check a direction you can do var hasNorthWall = dirs[1,2].HasFlag(Dirs.North);
@ScottChamberlain Added to the answer, Thank you.
Another tip useful tip. When you need to make your powers of 2 for your flags, just use the left shift operator [Flags] enum Dirs { North = 1<<0, South = 1<<1, East = 1<<2, West = 1<<3 }. It makes it a lot easier to read when you start getting in to enums that use a lot of possible flag values, for example SomeFlag = 1048576 vs SomeFlag = 1<<20.
@ScottChamberlain Well, I agree, it makes a big sense for guys that don't remember all powers of 2 up to 16 bits at least. :p
|
0

try that:

private EnumName[,] arrayName; 

Comments

0

This is how you declare and test for walls using an enum.

namespace ConsoleApplication1 { [Flags] enum Wall { North = 1, South = 2, East = 4, West = 8 } static class Program { static void Main(string[] args) { int grid = 10; var map=new Wall[grid, grid]; // fill in values here ... if(map[1, 2].HasFlag(Wall.North)) { // cell (2, 3) has a wall in the north direction } } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.