开发者

problem regarding assigning numbers to an enum variable

I've created a simple enum in C# as follows

enum Direction
{
    North,
    South,
    East,
    West
}

Now I'm creating a variable of this Direction enum as :

Direction D = (Direction)3;
Console.WriteLine(D.ToString());

Every thing goes fine and code works as expected and gives the following as output.

West

but now if I changes the code a bit like :

Direction D = (Direction)8;
Console.WriteLine(D.ToString());

it gives following as output :

8

So finally the questions came in my mind are:

  1. Why this is getting done when the max acceptable value is 3.
  2. If its getting accepted at time of compiling then why it's not throwing any exception while .net framework is such a robust framework yet.
  3. And at last but not the least, if all is not going expected why it's giving output 8.

Thanks in advance buddies :)

GUR开发者_Go百科U


Why this is getting done when the max acceptable value is 3.

This assumption is not correct. You can assign any value that's within the range of the enum's base type (here: int) to a variable of that enum type.

If its getting accepted at time of compiling then why it's not throwing any exception while .net framework is such a robust framework yet.

It doesn't throw an exception, because it's not an exceptional situation, but perfectly valid.

And at last but not the least, if all is not going expected why it's giving output 8.

Because there is no enum member that gives a name to the value 8.


If you don't want a enum value other than those with a name to be passed to a method, you should check the method's inputs:

void Move(Direction d)
{
    if (d != Direction.North && d != Direction.South &&
        d != Direction.East  && d != Direction.West)
    {
        throw new ArgumentOutOfRangeException("d");
    }

    // ...
}


Enums are just named constants and C# doesn't offer any range check if you cast a value to an enum.

1) There's no range check. Look at enums like a (usually) small set of names for a (usually) much larger set of numbers. I.e. C# lets you assign names to specific values, but it doesn't limit the allowable values, so an enum variable may take any value of the underlying type (default is int) if you cast it.

2) Same as 1) really

3) What else would you expect. You haven't assigned a name for that value.

You may want to check this question as well.


Normally when you declare an enum like that you set the values according to the list:

enum Direction{
North,
South,
East,
West}

Direction D = Direction.East;

What is your reasoning behind trying to set a value of 8?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜