Wednesday, April 30, 2008

Extracting string literals from Enum

public enum Users { Anonymous, Trainee, Developer, TeamLeader, Manager, Administrator}

A simple way to extracting the string constants from enum:

Type userType = typeof(Users);

// get names of users as string
string[] user = Enum.GetNames(userType);

// enum to string
string anonymous = Users.Anonymous.ToString();

// string to enum
Users manager = (Users)Enum.Parse(typeof(Users), "Manager", true);

No comments: