I want to create a generic method to serizlize a class to text (for use as part of a networking component)
The method should be something like:
public string SerializeToText<T>(T DataToSerialize);
The method contents would simply perform the xml serialization and I can do this. What I want to know is if I can check whether T can be serialized: preferably at compile time, but failing that, at run time.
The single most reliable way to test and see if an object was serializable is to serialize it. If it succeeds then the object was serializable, if it throws then it was not serializable.
Note this is not a predictor of future success but only of past success. It’s certainly possible for an object to change it’s state in a way to make it no longer serializable. For example
I wrote a lengthy blog article on the issues around determining if an object is or is no serializable. It goes over the issues with this type of an approach in depth.