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#?
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 + vtwill 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.WriteLineall 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).