Home > database >  How to instantiate a generic type in base class?
How to instantiate a generic type in base class?

Time:10-20

I have a built an XML parser which parses different types of products. The parser code is common for all product types (it deserializes the XML into Product type)

So I have created a generic base class called XmlParser

public abstract class XmlParser<TProduct> where TProduct : ProductBase
{
    public abstract TEntity Instanciate();
        
    private string _parserName;

    public XmlParser(string parserName)
    {
        _parserName = parserName;
    }

    public List<TProduct>Parse()
    {
        TEntity product = Instanciate(); // <-- I need to instantiate the Generic type here 
        // deserialize XML into product
    }
}

and a derived class:

public class CarXmlParser : XmlParser<Car>
{
    public CarXmlParser() : base("CarParse") {}

    public override Car Instanciate()
    {
        return new Car();
    }
}

Car is product type and is derived from ProductBase

In the base class, I need to instantiate TProduct. The only way I could do this was by creating an abstract method in the base class: public abstract TEntity Instanciate();. Obviously the child has to implement it.

Is there an easier way to instantiate the generic type? I have seen this question where they use new T constraint for the same purpose, however I was not able apply it to my example...

CodePudding user response:

If it has a default constructor, add the New Constraint, and new it up

The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

Example

public abstract class XmlParser<TProduct> 
    where TProduct : ProductBase, new()

...

public List<TProduct>Parse()
{
    var product = new TProduct();

    ...

CodePudding user response:

if it doesn't have new() constraint you can use the following:

 Activator.CreateInstance<T>();
  • Related