Create an Enum instance from String

  • Thread starter Thread starter PJ
  • Start date Start date
P

PJ

I have a couple of different enums. Let's say:

enum Beer
{
Bud, Coors, Michelob
}
enum Woman
{
Blonde, Brunnette, Redhead
}

I want to create an instance of one of these enums from a string. I don't
know which enum it's going to be. I just have a string that tells me.

Say: "Beer.Michelob"

How would I accomplish this? Thank you.

~PJ
 
PJ said:
I have a couple of different enums. Let's say:

enum Beer
{
Bud, Coors, Michelob
}
enum Woman
{
Blonde, Brunnette, Redhead
}

I want to create an instance of one of these enums from a string. I don't
know which enum it's going to be. I just have a string that tells me.

Say: "Beer.Michelob"

How would I accomplish this? Thank you.

Use String.Split to split it into the enum name and the value name,
then use Type.GetType to convert the enum name into a Type reference,
and Enum.Parse to convert the value name into a value.
 
The type I am trying to create is defined in a referenced assembly. This
does not seem to work with referenced assemblies, even when using the
Assembly Qualified Name. How do I reconcile this?

Thanks
~PJ
 
PJ said:
The type I am trying to create is defined in a referenced assembly. This
does not seem to work with referenced assemblies, even when using the
Assembly Qualified Name. How do I reconcile this?

If you use the full AQN, it should work. Could you post a short but
complete program which demonstrates the problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 
I have discovered the issue. Apparently, there has been a change in 2.0.
In 1.1, you could reference the type just by declaring it's name as long as
it was part of a referenced assembly. Now, you must include the Assembly
name. i.e.

Type.GetType("MyCompany.MyProject.MyType") does not work and must be:

Type.GetType("MyCompany.MyProject.MyType, MyCompany.MyProject")
 
PJ said:
I have discovered the issue. Apparently, there has been a change in 2.0.
In 1.1, you could reference the type just by declaring it's name as long as
it was part of a referenced assembly.

No, you couldn't - or at least, I've seen that fail several times under
1.1, and never seen it succeed. I had to answer the problems of several
people who ran up against that exact problem. Type.GetType(string) only
looks in mscorlib and the currently executing assembly unless you
specify the assembly name.
 
Back
Top