I have the following problem. I have an Enum which defines types of possible objects whom all (the objects) inherits from a base class. Now, I know the type of the object I would like to create.
However, I would like to prevent code duplicity. So in order to do so, I wanted to do the following:
Type myType = null;
string myParemeters = "json valid value" // the value to deserialize from
switch (enumType)
{
case EnumType.X:
myType = typeof(X);
break;
case EnumType.Y:
myType = typeof(Y);
break;
}
if (myType != null)
{
myRequest = JsonConvert.DeserializeObject<myType>(myParameters);
}
while myRequest is an object which can be X, Y or any other value listed in the Enum (because they are all inherit from a base class).
However, it can't be compiled since I get the following error:
The type or namespace name 'myType' could not be found (are you missing a using directive or an assembly reference?)
My solution now is to create the instance in every case.. but I really don't want to do it.
Does anybody know how this problem can be solved?