Casting an Enumeration (Reflection)

A

Alicia

Hi all,

I have a problem with an Enum and Reflection. I am using an Xml and
Reflection to create some controls, and to set their properties. All
goes well until I encounter one property which is defined like this:

public enum MyType {
Alpha = 0,
Beta = 1
}

public class MyClass {
private MyType _type;

public MyType theType {
get {
return _type;
}
set {
_type = value;
}
}
}

In another place I am using reflection to use a MyClass instance.

....
Control _control = (Control)
Assembly.LoadWithPartialName(assembly).CreateInstance(controlType);
Type type = _control.GetType();
PropertyInfo pi = type.GetProperty(prop.name);
pi.SetValue(_control, convertValue2PropertyType(valueToMap,
pi.PropertyType), null);

.....

the convertValue2PropertyType works fine on a lot of property types,
it does something like:

private object convertValue2PropertyType(string propValue, Type
propType)
{
if (propType.FullName == "System.Int16")
return System.Convert.ToInt16(propValue);
.....
and so on
.....
}

But when the propType.BaseType is System.Enum I cannot cast from the
propValue(which is an integer) to the proper MyType.

So if I have propValue == 0, I would like to be able to return
MyType.Alpha - Of course, in a programatic way, something like:

if (propType.BaseType.FullName == "System.Enum")
{
return (propType) System.Convert.ToInt32(propValue);
}

How do I achieve this?

TIA!
Alicia
 
N

Nicholas Paldino [.NET/C# MVP]

Alicia,

I don't see how you could return a strongly typed enumeration value
(since you are reflecting on the type, right). You could return object,
however, and then parse the value from the text ("3" to an int that equals
3). Once you have that, you can pass that value to the static ToObject
method on the Enum class, which will convert the value to the corresponding
value in the enumeration.

Hope this helps.
 
A

Alicia M

Hi Nicholas,

Actually I try to pass 3 to the SetValue method, so the call in the end
is like:

pi.SetValue(_control, 3, null);

But the SetValue method will fail with (I can't remember the exact error
mesage) something like "type of value doesn't match the type expected on
the property". Which is true, my property expects a MyType value (even
if that is, in fact, an int), while I'm passing an int.

Thank you for your help,
Alicia
 
A

Alicia

Yup, just discovered the System.Enum.Parse method over
the weekend and it works perfect.

Thanks anyway,
Alicia
 
Top