Generic Classes vs Generic Methods

Viewed 1351

I'm designing a class capable of deserializing some file, and I'm wondering what would be the implications of this two options:

// option 1 - generic class
public class XmlConfigurationManager<T>
{
    public T ReadConfigurationAndWriteDefault(string configurationPath, Func<T> defaultConfiguration)
    {
        ...
    }

    public T Deserialize(string configurationPath)
    {
        ...
    }
}

// option 2 - generic methods in non generic class
public class XmlConfigurationManager
{
    public T ReadConfigurationAndWriteDefault<T>(string configurationPath, Func<T> defaultConfiguration)
    {
        ...
    }

    public T Deserialize<T>(string configurationPath)
    {
        ...
    }
}

I can't seem to find any hint on the differences between the two.

How do this two options compare? There would be any difference? Are there any notable points to keep in mind when evaluating the design?

1 Answers

I can think of one difference right away:

  • Generic class: You'll have to instanciate an object with a certain type for every type of file you want to deserialize to. Although you'll be able to hold type-specific parameters in case you use the instance long term.
  • Generic method: You'll instanciate the class once and use the generic method for as much types as you want (assuming you'll handle the difference of types, if any).

For example, if you want to simply deserialize the content of a file (json) to an object, a generic method would be enough as the needed type doesn't change anything.

Related