C #: do enumerations as strings or integers depending on context

If I have an enumeration:

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

and then do:

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

What should be output in C #?

+3
source share
4 answers

By default, the base type is enum. It can also be a byte, sbyte, short, ushort, uint, long or ulong, if explicitly specified.

X = X + vt it will be wrong, because it must be explicit.

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

"I ride a bike with 12 people."

because when using Console.WriteLineall the methods of the ToString () variables are called so that the string representation of Enum is specified (the enumeration is 2, which corresponds to Bike, therefore Bike is returned).

0

X = X + vt; vt int. "I travel in a " + vt + " with " + X + " people." vt vt.ToString(), .

+6

. , !

0

, .

, enum , , . public enum VehicleType : ushort.

, Enum (, GetName(), IsDefined() Parse()).

, , int , ? : http://msdn.microsoft.com/en-us/library/sbbt4032.aspx ( , Flags).

-1
source

Source: https://habr.com/ru/post/1744295/


All Articles