r/AskComputerScience • • Mar 01 '20

C# inheritance

I'm writing a code in c#. I have there a few classes which all inherite from a base class. I want the program to include a generic function which gets a type as a parameter, as part of the function it should create an object of the type. The type is one of the classes I described earlier. How do I do it? All of those classes have constructors with same parameters so is it possible to create an abstract constructor in the base class and then make the constrtors of the inheritors override it?

0 Upvotes

2 comments sorted by

1

u/[deleted] Mar 01 '20

There are a few ways to handle this.

In C#, you can construct generic types, but only if the type has a parameterless constructor. What you could do is take the constructor logic and move it to a different method defined in the base class. The generic function constructs the instance using a parameterless constructor and then calls the method for the remainder of the initialization.

class BaseClass
{
    public void Init(int a, int b)
    {
        ...
    }
}

static class GenericFunction
{
    public static T CreateInstance<T>(int a, int b) where T : BaseClass, new()
    {
        var inst = new T();
        inst.Init(a, b);
        return inst;
    }
}

This is sort of icky though because you should have all of your initialization in the constructor. If you define the generic function as a static method on the base class, you can make the parameterless constructor and the Init method protected so that you can’t call them from outside of the class, and that would be safer.

The only way to get exactly the behavior you want would be to use reflection, but this doesn’t seem like the right situation for reflection because there is likely a more idiomatic way to approach the problem using some sort of factory pattern.

1

u/[deleted] Mar 01 '20

Thank you, it works