Reputation: 105
I have the following static method:
public static cols Parse(string[] inCols, int[] dat)
{
cols c = new cols();
PropertyInfo[] properties = typeof(cols).GetProperties();
for (int i = 0; i < inCols.Length; i++)
{
PropertyInfo prop = properties.Single(a => a.Name == inCols[i]);
var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var safeValue = Convert.ChangeType(dat[i], t);
prop.SetValue(c, safeValue);
}
return c;
}
Here, the properties of "cols" class are nullable Enum types.
The method has two incoming parameters (inCols and dat). The inCols contains the properties names as string, the dat contains their values as int.
The method's task would be to based on the method's name, it assigns the proper values the the nullable enum type.
I receive the following error message: System.InvalidCastException: 'Invalid cast from 'System.Int32' to '<my enum type>'.'
This is strange, because the value should be 0, which is fine for the enum becuase it is its first value.
Does any of you have any idea?
Thanks! Gabor
Upvotes: 1
Views: 1258
Reputation: 3738
Because you're dealing only with Enums
, you may simply change your code to this:
var safeValue = Enum.ToObject(t, dat[i]);
Upvotes: 3