简体   繁体   中英

C#: do enums cast themselves as strings or integers as appropriate in the context

If I have the enum:

public enum VehicleType
{
    Car = 0,
    Boat = 1,
    Bike = 2,
    Spaceship = 3
}

and I then do:

int X = 10;
VehicleType vt = (VehicleType)2;
X = X + vt;
Console.WriteLine("I travel in a " + vt + " with " + X + " people.");

What should the output be in C#?

In X = X + vt; vt will be casted to int. In "I travel in a " + vt + " with " + X + " people." vt will be replaced to vt.ToString(), which will print the name of the enum.

An enum's base type is int by default. It can also be a byte, sbyte, short, ushort, uint, long, or ulong if explicitly specified.

X = X + vt will error because it needs to be an explicit cast.

If it were X += (int)vt; it would be:

"I travel in a Bike with 12 people."

because when using Console.WriteLine all variables' ToString() methods are called so the string representation of the Enum is given (enum is 2, that equates to Bike, so Bike is returned).

They are represented as integers. I wish they could be represented as objects!

As the others already mentioned you just get an integer.

That's because the base-type of an enum is an integer, but this can be changed to any other value type by eg public enum VehicleType : ushort .

To get some better handling with these names the Enum class has some handy functions (like GetName() , IsDefined() or Parse() ).

Just to answer the question So how can you say that the enum is being represented as an int in what you have just stated? from the comments: Take a look at http://msdn.microsoft.com/en-us/library/sbbt4032.aspx (especially take a decent look into the last example using Flags ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM