user1464139
user1464139

Reputation:

Is there a way I can get a string value out of an enum in C#

I have the following code:

public enum RoleType
{
    Default = 10,
    Guest = 20,
    User = 30,
    Admin = 40,
    Super = 50
}

Is there any way that I could get have some kind of toString method in the enum that would give me the strings "Default", "Guest" .. etc I don't mind to hard code these in one by one or even have a dictionary with the values hardcoded twice inside the enum. I would just like to keep everything self contained inside of my enum.

Upvotes: 2

Views: 108

Answers (4)

soloist
soloist

Reputation: 21

Use RoleType.Guest.ToString()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public enum RoleType {
        Default = 10,
        Guest = 20,
        User = 30,
        Admin = 40,
        Super = 50
    }


    class Program {
        static void Main(string[] args) {
            Console.WriteLine(RoleType.Guest.ToString());
            Console.ReadLine();
        }
    }

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 180877

How about ToString()?

Console.WriteLine(RoleType.User);

> User

Console.WriteLine(RoleType.User.ToString());

> User

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

string s1=Enum.GetNames(typeof(RoleType), object);

Upvotes: 0

Shahar Gvirtz
Shahar Gvirtz

Reputation: 2438

string str =Enum.GetName(typeof(RoleType), obj);

obj should be the value you want the name for

Upvotes: 0

Related Questions