Reputation: 946
I have an abstract object Item that has several children: RadioItem, CheckItem, etc.
Each item stores its own properties in a serialized JSON string property.
I'm trying to make a static class that can take in an Item, instantiate a new item from the JSON string and return that.
Right now I have the code looking something like this:
public static Item GetFreshItem(Item dirtyItem)
{
string itemProperties = dirtyItem.InitialItemSettingsJSON;
if (dirtyItem is RadioItem)
{
return JsonConvert.DeserializeObject<RadioItem>(itemProperties);
}
if (dirtyItem is CheckItem)
{
return JsonConvert.DeserializeObject<CheckItem>(itemProperties);
}
return null;
}
Is there a way to not have a long list of If (x is Type) and use a more dynamic single return statement depending on the type that was passed in?
I was thinking it'd be something like this (which doesn't work)
JsonConvert.DeserializeObject<typeOf(dirtyItem)>(itemProperties);
Upvotes: 0
Views: 1074
Reputation: 3683
You could also do:
public static T GetFreshItem<T>(T dirtyItem) where T:Item
{
string itemProperties = dirtyItem.InitialItemSettingsJSON;
return JsonConvert.DeserializeObject<T>(itemProperties);
}
This way you don't need a cast.
Upvotes: 0
Reputation: 56556
I think you're looking for the (string, Type)
overload of the deserialize method.
string itemProperties = dirtyItem.InitialItemSettingsJSON;
return (Item)JsonConvert.DeserializeObject(itemProperties, dirtyItem.GetType());
Upvotes: 3