i’m building a serialization component that uses reflection to build the serialized data, but i’m getting weird results from enumerated properties:
enum eDayFlags
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public eDayFlags DayFlags { get; set; }
Now for the real test
Obj Test = new Obj();
Test.DayFlags = eDayFlags.Friday;
Output of serialization is then:
DayFlags=Friday
But if i set two flags in my variable:
Obj Test = new Obj();
Test.DayFlags = eDayFlags.Friday;
Test.DayFlags |= eDayFlags.Monday;
Output of serialization is then:
DayFlags=34
What i am doing in the serialization component is pretty simple:
//Loop each property of the object
foreach (var prop in obj.GetType().GetProperties())
{
//Get the value of the property
var x = prop.GetValue(obj, null).ToString();
//Append it to the dictionnary encoded
if (x == null)
{
Properties.Add(HttpUtility.UrlEncode(prop.Name) + "=null");
}
else
{
Properties.Add(HttpUtility.UrlEncode(prop.Name) + "=" + HttpUtility.UrlEncode(x.ToString()));
}
}
Can anyone tell me how to get the real value of the variable from PropertyInfo.GetValue even if it’s an enumeration and there is only one value?
Thanks
You are getting the real value out – it’s just the conversion to a string which isn’t doing what you expect. The value returned by
prop.GetValuewill be the boxedeDayFlagsvalue.Do you want the numeric value from the enum? Cast it to an
int. You’re allowed to unbox an enum value to its underlying type.Note that your enum – which should probably be called
Days– ought to have[Flags]applied to it, given that it is a flags enum.