Code Analysis Warning CA1004 with generic method

Posted by Vaccano on Stack Overflow See other posts from Stack Overflow or by Vaccano
Published on 2010-06-03T14:34:49Z Indexed on 2010/06/03 15:44 UTC
Read the original article Hit count: 193

Filed under:
|
|

I have the following generic method:

// Load an object from the disk
public static T DeserializeObject<T>(String filename) where T : class
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

    try
    {
        TextReader textReader = new StreamReader(filename);
        var result = (T)xmlSerializer.Deserialize(textReader);
        textReader.Close();
        return result;
    }
    catch (FileNotFoundException)
    { }

    return null;
}

When I compile I get the following warning:
CA1004 : Microsoft.Design : Consider a design where 'MiscHelpers.DeserializeObject(string)' doesn't require explicit type parameter 'T' in any call to it.

I have considered this and I don't know a way to do what it requests with out limiting the types that can be deserialized. I freely admit that I might be missing an easy way to fix this.

But if I am not, then is my only recourse to suppress this warning? I have a clean project with no warnings or messages. I would like to keep it that way.

I guess I am asking "why this is a warning?" At best this seems like it should be a message. And even that seems a bit much. Either it can or it can't be fixed. If it can't then you are just stuck with the warning with no recourse but suppressing it. Am I wrong?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics