2 Replies - 3237 Views - Last Post: 19 January 2008 - 01:53 PM Rate Topic: -----

#1 kayaker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 11-October 07

declaring an enum whose associated vals are string rather than int

Posted 15 January 2008 - 10:53 AM

i am able to do this:

public enum EnumInt
		{
			INTVAL0 = 0,
			INTVAL1 = 1
		}



but i also want to do

public enum EnumStr
		{
			STRVAL0 = "Jack",
			STRVAL1 = "Jill"
		}



the compilation fails complaining "Cannot implicitly convert type 'string' to 'int'".

is there a workaround ?

thx,

- a -

Is This A Good Question/Topic? 0
  • +

Replies To: declaring an enum whose associated vals are string rather than int

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4187
  • View blog
  • Posts: 11,851
  • Joined: 18-April 07

Re: declaring an enum whose associated vals are string rather than int

Posted 15 January 2008 - 12:46 PM

That isn't possible in C#, you can use characters like 'A' which map to an integer, but full strings won't work. If you want to do this type of functionality, perhaps you should look at either constants or maybe a struct will work for your purpose.

One other thing you could try is setting up your enum like this...

		
public enum DatePart
{
	 YEAR = 0,
	 MONTH = 1,
	 DAY = 2,
	 HOUR = 3,
	 MIN = 4,
	 SEC = 5,
	 MILLI = 6
};



And use the following to make it seem like you are accessing the name using its value.

// Dp.ToString() will then be the value "SEC". So you could use the 5 to access and return a string.
// Just think of it as flipping it around.
DatePart dp = (DatePart)Enum.Parse(typeof(DatePart), "5", true);



Hope that helps you out. :)

"At DIC we be enum slaughtering code ninjas!" :snap:
Was This Post Helpful? 0
  • +
  • -

#3 gogole  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 131
  • Joined: 17-July 07

Re: declaring an enum whose associated vals are string rather than int

Posted 19 January 2008 - 01:53 PM

enums in c# are for labeling of *numerics* using strings(names) to make code more readable and easy to understand.strings should be inherently readable .
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1