Monday, September 9, 2019

C#- string,enum

String To Enum Conversion [C#]

This example shows how to convert enum values to string and reversely.

Enum to string

To convert enum to string use simply Enum.ToString method.
[C#]
Animal animal = Animal.Cat;
string str = animal.ToString();  // "Cat"

String to enum

To convert string to enum use static method Enum.Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
[C#]
string str = "Dog";
Animal animal = (Animal)Enum.Parse(typeof(Animal), str);  // Animal.Dog
Animal animal = (Animal)Enum.Parse(typeof(Animal), str, true); // case insensitive

No comments:

Post a Comment

API interview questions

  https://www.katalon.com/resources-center/blog/web-api-testing-interview-questions/ Top 50+ Web API Testing Interview Questions [Ultimate l...