@
@
@insighter2021-06-27 23:37:38
C++ / C#
@insighter, 2021-06-27 23:37:38

How to correctly inherit from a generic class without a compiler error?

I pulled out code from my application (without unnecessary specifics), which leads to a compiler error.

public class DataObject
{
    public string Id { get; set; }
    public int ObjType { get; set; }
}

public class ReferredObject : DataObject
{
    public string Name { get; set; }
     public string Remark { get; set; }
}

public class Model<TDataObject> where TDataObject : DataObject, new()
{
}

// строка ниже, ошибка компилятора: CS0310
public class RefferedObjectModel<TDataObject> : Model<TDataObject>
    where TDataObject : ReferredObject
{
}


Error text:

'TDataObject' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TDataObject' in the generic type or method 'Program.Model'


Semantically "ReferredObject" can be considered abstract, but syntactically it isn't, what's the compiler's claim?
And yes, it is clear that the whole point is in the "new ()" option specified when declaring the Model class.

Tell me how to implement such functionality, given that the RefferedObjectModel is not the final class from which inheritance will occur?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
insighter, 2021-06-28
_

Thanks Anton Baryshev for the solution, you need to add the new () option

public class RefferedObjectModel<TDataObject> : Model<TDataObject>
    where TDataObject : ReferredObject, new()

V
Vasily Bannikov, 2021-06-27
@vabka

what is the requirement of the compiler?

It doesn't have a public parameterless constructor.
But I generally do not advise using the new () constraint, because it slows down the code very much.

A
Anton Baryshev, 2021-06-27
@AVollane

Hello.
Do you really need the type in the generic class declaration to have a public parameterless constructor? If you remove , then everything is without errors:, new()

public class Model<TDataObject> where TDataObject : DataObject
    {
        public Model()
        {

        }
    }

Can you just remove this restriction, or is it necessary?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question