tkrasinger

I am setting the values from my DataRow into an object using Reflection. But my class has following Property:

public MyEnum EnumProperty

{

get; set;

}

How can I convert the Int32Value into the property enum type, using the following code:

ItemSetter {

...

else if (pInfo.PropertyType.IsEnum) {

SetEnum(item, pInfo, pInfo.PropertyType, rowValue); //enum

}

else if (pInfo.PropertyType.IsGenericType && pInfo.PropertyType.GetGenericArguments()[0].IsEnum) {

SetEnum(item,pInfo, pInfo.PropertyType.GetGenericArguments()[0], rowValue); //nullable enum

}

...

}

protected virtual void SetEnum(T item, PropertyInfo pInfo, System.Type enumType, Object rowValue){

pInfo.SetValue(item,rowValue) // How to cast

}



Re: .NET Base Class Library Convert Int32 to Unknown Enum

Salvatore Di Fazio

You can use the Enum.Parse to get a enum value from a string.

To get the enum value from a int32 look at this tutorial:

http://blogs.msdn.com/abhinaba/archive/2005/10/20/483000.aspx




Re: .NET Base Class Library Convert Int32 to Unknown Enum

nobugz

You don't have to do anything special, just assign the integer value:

using System;
using System.Reflection;

namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
int value = 1;
Test obj = new Test();
PropertyInfo pi = typeof(Test).GetProperty("Prop");
pi.SetValue(obj, value, null);
Console.WriteLine(obj.Prop);
Console.ReadLine();
}

public enum MyEnum {
zero,
one,
two,
three
}

public class Test {
private MyEnum mProp;
public MyEnum Prop {
get { return mProp; }
set { mProp = value; }
}
}
}
}






Re: .NET Base Class Library Convert Int32 to Unknown Enum

tkrasinger

According to article:

I may be able to resolve the name via the value when using a "normal" enum, but what should I do, if the Enum is a flagged enum I just can't resolve the name ...





Re: .NET Base Class Library Convert Int32 to Unknown Enum

tkrasinger

@nobugz: Could you try this with this Enum:

[Flags]

public enum CustomerRights {

/// <summary>

/// No rights are assigned

/// </summary>

[EnumMember]

None = 0,

/// <summary>

/// May manage all customer-visible data, including subscriptions, users, addresses, etc.

/// </summary>

[EnumMember]

CustomerAdmin = (1 << 0),

/// <summary>

/// May create sub-users and assign them subscriptions, for which he has been granted

/// access

/// </summary>

[EnumMember]

ManageSubUsers = (1 << 1),

/// <summary>

/// May manage all customer subscriptions and assign them to any user (even outside his

/// hierarchy)

/// </summary>

[EnumMember]

ManageCustomerSubscriptions = (1 << 2),

/// <summary>

/// Auto-subscribed to all product-subscriptions of the user's company (dbo.customer).

/// The authentication-process will map all active customer-subsciptions to this user, if

/// this flag is set

/// </summary>

[EnumMember]

AutoSubscribed = (1 << 3),

}

and the property

public Enum.CustomerRights CustomerRights {

get { return this.p_CustomerRights; }

set { this.p_CustomerRights = value; }

}





Re: .NET Base Class Library Convert Int32 to Unknown Enum

salvodif

I didn't understand. Maybe this code can help you

Code Block

// demonstrates explicit cast
// of int to Enum

public void GetEnumFromUser()
{
Console.WriteLine("\n----------------");
Console.WriteLine("Volume Settings:");
Console.WriteLine("----------------\n");

Console.Write(@"
1 - Low
2 - Medium
3 - High

Please select one (1, 2, or 3): ");

// get value user provided
string volString = Console.ReadLine();
int volInt = Int32.Parse(volString);

// perform explicit cast from
// int to Volume enum type
MyEnum myEnum = (MyEnum )volInt;

Console.WriteLine();

// make decision based
// on enum value
switch (myEnum )
{
case MyEnum .Low:
Console.WriteLine("The volume has been turned Down.");
break;
case MyEnum .Medium:
Console.WriteLine("The volume is in the middle.");
break;
case MyEnum .High:
Console.WriteLine("The volume has been turned up.");
break;
}

Console.WriteLine();
}





Re: .NET Base Class Library Convert Int32 to Unknown Enum

tkrasinger

@Salvodif: The type of the enum is unknown, so I can't write the line

MyEnum myEnum = (MyEnum )volInt;





Re: .NET Base Class Library Convert Int32 to Unknown Enum

salvodif

Ah okkey.

So you need to implement an Abstract Factory method, something like this

Code Block

public static MessageFactory GetFactory(type enumtype)

{

switch (enumtype)

{

case enum.EMAIL:

return new EMailFactory();

case enum.SMS:

return new SmsFactory();

default:

throw new NotImplementedException(string.Format("The class was not implemented: {0}", m.ToString()));

}

}

look at

http://en.wikipedia.org/wiki/Abstract_factory_pattern

to understand how the pattern works.





Re: .NET Base Class Library Convert Int32 to Unknown Enum

Salvatore Di Fazio

I wrong my account...

If the answer had help you, please vote this post with the name "Salvatore Di Fazio" and not "SalvoDif"

Thank you





Re: .NET Base Class Library Convert Int32 to Unknown Enum

tkrasinger

You don't really expect me to write a factory for every enum I use

The only thing I know what to do, is to write the Line "(Enum)obj = (Enum)value" somehow using a CodeGenerator ...





Re: .NET Base Class Library Convert Int32 to Unknown Enum

Salvatore Di Fazio

You can do that, but after you will need to get the type of enum from the object

Code Block

; when you will have the type you can do:

switch(enumType)

{

case EnumFirst:

break;

case EnumSecond:

break;

default:

}

I don't think another solution right now





Re: .NET Base Class Library Convert Int32 to Unknown Enum

nobugz

It still works without problems if you use [Flags]:

using System;
using System.Reflection;

namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
int value = 15;
Test obj = new Test();
PropertyInfo pi = typeof(Test).GetProperty("Prop");
pi.SetValue(obj, value, null);
Console.WriteLine(obj.Prop);
Console.ReadLine();
}
[Flags]
public enum MyEnum {
zero = 1,
one = 2,
two = 4,
three = 8
}

public class Test {
private MyEnum mProp;
public MyEnum Prop {
get { return mProp; }
set { mProp = value; }
}
}
}
}





Re: .NET Base Class Library Convert Int32 to Unknown Enum

tkrasinger

Try this and you will notice my problem (sorry to be late but I fixed it otherwise meanwhile):

Code Block

using System;

using System.Reflection;

namespace Testing {

class TestCenter {

static void Main(string[] args) {

try {

int value = 1;

MyClass obj = new MyClass();

PropertyInfo pi = obj.GetType().GetProperty("MyEnumProperty");

pi.SetValue(obj, value, null);

Console.WriteLine(obj.MyEnumProperty);

Console.ReadLine();

}

catch (Exception ex) {

Console.WriteLine("Setting nullable enum property caused an error: " + ex.Message);

try {

int value = 1;

MyClass obj = new MyClass();

PropertyInfo pi = obj.GetType().GetProperty("SecondProperty");

pi.SetValue(obj, value, null);

Console.WriteLine(obj.SecondProperty);

Console.ReadLine();

}

catch (Exception e) {

Console.WriteLine("Setting enum property caused an error: " + e.Message);

}

}

}

}

[Flags]

public enum MyEnum {

None = 0,

FirstValue = (1 << 0),

SecondValue = (1 << 1),

ThirdValue = (1 << 2),

FourthValue = (1 << 4)

}

public class MyClass {

private MyEnum p_MyEnumProperty;

public MyEnum MyEnumProperty {

get { return this.p_MyEnumProperty; }

set { this.p_MyEnumProperty = value; }

}

private MyEnum p_SecondProperty;

public MyEnum SecondProperty {

get { return this.p_SecondProperty; }

set { this.p_SecondProperty = value; }

}

}

}





Re: .NET Base Class Library Convert Int32 to Unknown Enum

tkrasinger

Any suggestions on how to solve that easily




Re: .NET Base Class Library Convert Int32 to Unknown Enum

ericrtodd

Trying to fit it into your situation:

Code Block

void SetEnumPropertyValue(Type enumType,object target,PropertyInfo property,int value) {

property.SetValue(target,Enum.ToObject(enumType,value),null);

}