SerializationInfo extension method for typifing GetValue

This is a handy extension method I recurrently use to help me with the deserialization process. It helps to keep the code clean on the serialization constructor by strongly typing the GetValue method on the SerializationInfo class.

/// <summary>
/// Static class that contains extensions to <seealso cref="SerializationInfo"/>.
/// </summary>
public static class SerializationInfoExtensions
{
    /// <summary>
    /// Retrieves a value from the SerializationInfo store.
    /// </summary>
    /// <typeparam name="T">The type of the value to retrieve.</typeparam>
    /// <param name="info">The SerializationInfo instance.</param>
    /// <param name="name">The name of the parameter to retrieve.</param>
    /// <returns>The deserialized instance of T.</returns>
    public static T GetValue<T>(this SerializationInfo info, string name)
    {
        return (T) info.GetValue(name, typeof(T));
    }
}

When this extension method is in scope we can easily retrieve strongly typed data from SerializationInfo:

appConfiguration = info.GetValue<ApplicationConfiguration>("AppConfiguration");
appPreferences = info.GetValue<AppPreferences>("AppPreferences");

This is just a small sample on how helpful and powerful extension methods can be!

Leave a Reply

Your email address will not be published. Required fields are marked *