4

I am writing some code to read values from a database and convert them into an object.

My object has a few members whose type is custom defined enums.

I am trying something like this in order to convert a string variable to an enum:

var castTo = fieldInfo.PropertyType.GetType(); //returns a Type object, e.g. MyEnum
var parsedEnum = (castTo) Enum.Parse(castTo, valueFromSql);

The problem is that compiler wouldn't accept a variable that contains a Type object.

There is no problem if instead of the castTo variable I use an enum name, but it needs to be defined at runtime.

1 Answer 1

3

You could try that:

var castTo = fieldInfo.PropertyType.GetType(); 
var parsedEnum = Convert.ChangeType(Enum.Parse(castTo, valueFromSql), castTo);

More information about changing type can be found here: https://msdn.microsoft.com/en-us/library/system.convert.changetype(v=vs.110).aspx

There should be also a workaround for situation where database contains value that doesn't exists in your enum. Application will crash, as it will be not possible to do casting then.

Sign up to request clarification or add additional context in comments.

Comments