Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple compare if an enum is in a list of enums

Tags:

c#

enums

I have the following enum:

public enum Materials { Wood, Stone, Earth, Water, Lava, Air }

Now I have 3materials on which i could walk (wood stone earth) and 3 which arent walkable (water lava air)

I would like to make it possible to compare if a flag is one of the three.

At the moment, this is how I do it:

Materials myMat = Materials.Earth;
if ( myMat == Materials.Earth || myMat == Materials.Wood || myMat == Materials.Stone)
{
    I can walk on myMat...
}

isnt it possible to create a new flag like Materials.Walkable which would include these three materials so I can just use

if ( myMat == Materials.Walkable )

If this is possible, how can I do that?

Thanks in advance ;)

like image 896
Xavjer Avatar asked Oct 25 '11 14:10

Xavjer


1 Answers

You could create an extension method:

public static bool IsWalkable(this Materials myMat )
{
    return myMat == Materials.Earth || myMat == Materials.Wood || myMat == Materials.Stone; 

    // alternatively:
    return new[] { Materials.Earth,  Materials.Wood,  Materials.Stone }.Contains(myMat);
}

And use it as:

Materials myMat = ...
bool isMyMatWalkable = myMat.IsWalkable();

If you like, you could also use a [Flags] enum:

[Flags]
public enum Materials
{
   None = 0,
   Wood = 1,
   Stone = 1 << 1,
   Earth = 1 << 2,
   Water = 1 << 3,
   Lava = 1 << 4,
   Air = 1 << 5,
   Walkable = Wood | Earth | Stone
}

And then you can do:

Materials myMat = ..
bool isMyMatWalkable = (myMat & Materials.Walkable) != Materials.None;
like image 186
Ani Avatar answered Sep 30 '22 16:09

Ani