public enum VehicleData { Dodge = 15001, BMW = 15002, Toyota = 15003 }
I want to get above values 15001, 15002, 15003 in string array as shown below:
string[] arr = { "15001", "15002", "15003" };
I tried below command but that gave me array of names instead of values.
string[] aaa = (string[]) Enum.GetNames(typeof(VehicleData));
I also tried string[] aaa = (string[]) Enum.GetValues(typeof(VehicleData));
but that didn't work too.
Any suggestions?
We can convert an enum to string by calling the ToString() method of an Enum.
Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.
What about Enum.GetNames?
string[] cars = System.Enum.GetNames( typeof( VehicleData ) );
Give it a try ;)
Use GetValues
Enum.GetValues(typeof(VehicleData)) .Cast<int>() .Select(x => x.ToString()) .ToArray();
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With