Sorry if I've worded the question a bit odd! Basically, I have a serializable class that has a single field at this current time, but will definitely gain more in the future as we add features to the system. The serialization process will be used for both passing instances to a WCF service, and for reading/writing it from/to file. Of course, the latter may be a big problem if I'm continually updating the class with extra fields.
Luckily, I think I've solved the problem by adding a try/catch block around the field setter in the constructor, which I'll also do for any other fields that are added to the class.
/// <summary>
/// Represents launch options supplied to an executable.
/// </summary>
[Serializable]
public sealed class ExecutableLaunchOptions : ISerializable
{
/// <summary>
/// Creates a new set of executable launch options.
/// </summary>
public ExecutableLaunchOptions() { }
/// <summary>
/// Creates a new set of executable launch options via deserialization.
/// </summary>
/// <param name="info">the serialization information.</param>
/// <param name="context">the streaming context.</param>
public ExecutableLaunchOptions(
SerializationInfo info, StreamingContext context) : this()
{
// Get the value of the window style from the serialization information.
try { this.windowStyle = (ProcessWindowStyle)info.GetValue(nameof(this.windowStyle), typeof(ProcessWindowStyle)); } catch { }
}
// Instance variables.
private ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal;
/// <summary>
/// Gets or sets the window style to apply to the executable when it launches.
/// </summary>
public ProcessWindowStyle WindowStyle
{
get { return this.windowStyle; }
set { this.windowStyle = value; }
}
/// <summary>
/// Gets the information required for the serialization of this set of launch options.
/// </summary>
/// <param name="info">the serialization information.</param>
/// <param name="context">the streaming context.</param>
public void GetObjectData(
SerializationInfo info, StreamingContext context)
{
// Add the value of the window style to the serialization information.
info.AddValue(nameof(this.windowStyle), this.windowStyle, typeof(ProcessWindowStyle));
}
}
I'm guessing this will allow me to retain backwards-compatibility with files containing instances of previous versions of the class when I deserialize them, as the code will simply throw and subsequently catch exceptions for each field that doesn't exist in the serialization information, leaving their values at their default. Am I correct here, or am I missing something?