Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In recent versions of .NET, I can retrieve the enum value this way:

C#
public enum Packers
{
    Aaron_Rodgers = 12,
    Eddie_Lacy = 26,
    Jordy_Nelson = 87,
    Candle_Robb = 18,
    Clay_Matthews = 52,
    Julius_Peppers = 56
};

private void button4253147968_Click(object sender, EventArgs e)
{
    int packerNum = Convert.ToInt32(textBoxPackerNum.Text);
    String packerName = Enum.GetName(typeof(Packers), packerNum);
    MessageBox.Show(String.Format("Packer with number {0} is {1}", packerNum, packerName));
}


Entering "52" in textBoxPackerNum shows me "Packer with number 52 is Clay_Matthews" etc.

However, GetName() is not available for Enum in .NET 3.5

What can be done in older versions of .NET to retrieve this value?
Posted
Updated 13-Nov-14 12:09pm
v2
Comments
Kornfeld Eliyahu Peter 13-Nov-14 17:49pm    
GetName is there since 2.0 - http://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.80).aspx
B. Clay Shannon 13-Nov-14 17:52pm    
Strange...it won't compile, not does it afford me a "Resolve" with the context menu...maybe because the target platform is Windows CE; I should have mentioned that, I reckon.
Kornfeld Eliyahu Peter 13-Nov-14 18:03pm    
Enum.ToObject(typeof(Packers), 52).ToString();
This should work on any CF version...
B. Clay Shannon 13-Nov-14 18:24pm    
Yep, that works:

Packers pickedAPeckOfPickledPeppers = Packers.Julius_Peppers;
String s = Enum.ToObject(typeof(Packers), pickedAPeckOfPickledPeppers).ToString();
MessageBox.Show(String.Format("Packer passed is {0}", s));
PIEBALDconsult 13-Nov-14 18:40pm    
Just cast it.

1 solution

First of all, this is not what's Enum for. Using enum for such a task is really not a good idea. Let's suppose you have pnly given us a bad example...

This is working in 3.5 (and 3.5 CF) also:
C#
int x = 52;
Console.WriteLine(((Packers)x).ToString());


If you want to have something similar like GetNames in CF, start here: http://www.nickharris.net/index.php/2010/01/07/enum-getnames-in-net-compact-framework-3-5/[^] and here: http://stackoverflow.com/questions/8835264/how-to-enum-getvalues-in-net-3-5[^]
 
Share this answer
 
v2
Comments
BillWoodruff 14-Nov-14 2:16am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900