Matthew
Matthew

Reputation: 180

C# How to use Enums like in C++?

In C++ I can have an enum like this

enum RoomItems {
  WALL = 0,
  EMPTY = 1,
  START = 2,
  LOCK = 3,
  EXIT = 4
};

And then use it in the code like this:

Room temp = new Room({ WALL, START, LOCK });

Here's how I would do that in C# (to my current knowledge)

Room temp = new Room(new List<RoomItems>() { RoomItems.WALL, RoomItems.START, RoomItems.LOCK });

This is quite annoying when you have for example, large lists of these "items". In the C++ version of this program of mine, the rooms can have Item counts in the 20's, and while in my C++ code it still looks quite neat, in the C# version of my program, the code lines would just be way too long.

Is there a way I can use enums without using their name (as in without RoomItems.*), and if not, then is there a better alternative?

Upvotes: 0

Views: 120

Answers (3)

TVOHM
TVOHM

Reputation: 2742

You can initialize your room with a collection initializer:

using static YourNameSpace.RoomItems;

var temp = new Room() { WALL, START, LOCK };

if your room class implements IEnumerable and exposes a public add method:

class Room : IEnumerable<RoomItems>
{
    List<RoomItems> items = new List<RoomItems>();

    public void Add(RoomItems item)
    {
        items.Add(item);
    }

    public IEnumerator<RoomItems> GetEnumerator()
    {
        return items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Edit: becomes even more similar if you add mbj's using static directive.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56393

Yes, you can using params instead of passing a list. Assuming the Room constructor is defined as:

public Room(params RoomItems[] items){ ... }

you can then do:

Room temp = new Room(WALL, START, LOCK );

Note that a static import (AKA, using static directive) of RoomItems is needed otherwise you'll have to prefix the full name as in:

Room temp = new Room(RoomItems.WALL, RoomItems.START, RoomItems.LOCK );

Upvotes: 3

mbj
mbj

Reputation: 1015

What you're looking for, being able to reference members of a type without specifying the type name, is supported starting with C# 6.0, through the using static directive.

In the file where your enum is being referenced:

using static YourNameSpace.RoomItems;

[...]

var temp = new Room(new [] { WALL, START, LOCK });

(This passes the items as an array instead of a List, so make sure your Room constructor accepts IEnumerable<RoomItem>. You can use .ToList() if you absolutely need to use list-specific features in the constructor.)

Upvotes: 3

Related Questions