Monday, 22 January 2018

C# casting from parent to child object

For some reason I've never had to do this before (not that I can remember anyway), and it feels like I should have. I have a Child object that inherits from Parent. I want to turn an instance of a Parent object that I already have into a Child. I thought this might just be a simple cast but it doesn't work.

This SO post  was most helpful, and the neatest solution seemed to be this technique, serializing to json, and then back again:

 var serializedParent = JsonConvert.SerializeObject(parentInstance); 
 Child c  = JsonConvert.DeserializeObject<child>(serializedParent);