Reputation: 23295
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#?
Upvotes: 3
Views: 164
Reputation: 45119
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 e.g. 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).
Upvotes: -1
Reputation: 17038
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).
Upvotes: 0
Reputation: 14099
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.
Upvotes: 6
Reputation: 1195
They are represented as integers. I wish they could be represented as objects!
Upvotes: 0