PDA

Click to See Complete Forum and Search --> : Enum type from (e.g.) string???


Jhd.Honza
Mar 29th, 2002, 11:11 AM
Well, let's say I would like to do something like this:


enum Fruit {Apple, Orange, Banana}
enum Vegetable {Onion, Carrot, Cabbage}

string GetItemName(int Index, string category)
{
return ((category)Index).ToString();
}
[/b]


I hope this illustrates the problem...

I need to return "Cabbage" passing 2,"Vegetable" to the function

Scott Penner
Mar 30th, 2002, 09:51 AM
Sorry I don't have the time to work this out right now, but you should look up the Enum class. There are a lot of static methods to help you determine if an index or string is part of an enum and also to convert enums to string and integers etc.

I can figure this out next week if you're still needing help.

Jhd.Honza
Mar 30th, 2002, 02:04 PM
Well, I don't have problems with returning index of any enum member.

Actually, if you look to the example more carefully, you would find out the issue is (probably) behind the enum class.

I need to tell C# compiler the name of enum to use by (string) variable.

Scott Penner
Mar 31st, 2002, 09:22 PM
If you want help, you might want to use more tact in the future.
Of course I read your post.
There is a function in the unum class to return an enum index from the string. There are also functions to check the type of a passed enum.

Hope that helps. I was going to figure it out for you tomorrow, but oh well...

DevGrp
Apr 4th, 2002, 01:04 PM
Try using an indexer in a class or a struct.

Jhd.Honza
Apr 5th, 2002, 03:55 PM
At first I would like to apologize to Scott if he feels umbraged. I am sure he read the post and tried to help as possible. I was just in a hurry and I also think my previous skills with this way of support were unfortunately not so good. However, I really appreciate every suggestion to the question discussed.




To DevGrp: As you said, indexer can be used in a class or a struct, but I am afraid about using it with enum type.

Scott Penner
Apr 5th, 2002, 05:38 PM
OK here we go...
No hard feelings? :)


static string GetItemName(int Index, string Category)
{
// The name of the object must be explicitly specified, so the Category
// must have the prefix of the NameSpace,Class and a "+" (not sure why the +)
string TestString = "EnumTestNamespace.EnumTest+" + Category ;
string ReturnVal = "";

// Need the error check in case the category doesn't exist
try
{
// Creates a type from the string and parses the index / type into an Enum
// Then we turn the enum into a string for return...
ReturnVal = Enum.Parse(Type.GetType(TestString),Index.ToString()).ToString();
}
catch
{
ReturnVal = "Not found";
}

return ReturnVal;
}

Jhd.Honza
Apr 11th, 2002, 02:26 PM
Well, thank you Scott, you solved the problem! :D

It works even without EnumTestNamespace.EnumTest :)