Aleksa Kojadinovic
Aleksa Kojadinovic

Reputation: 337

Issue when inheriting abstract generic class

I have an abstract generic class:

public abstract class A<T> where T : class, new()
{
    public A (IEnumerable<T>_Data)
    {
         this.Data = _Data;
    }
     
    private IEnumerable<T>_data;

    public IEnumerable<T> Data
    {
        get { return _data; }
        set { _data = value;}
    }
}

Then when I inherit from that class:

public class B<T> : A<T> where T : class, new() 
{
}

I get an error:

There is not argument that corresponds to the required formal parameter '_Data' of 'A.A(IEnumerable)'

in the 'B' class.

Upvotes: 0

Views: 60

Answers (3)

Ashley John
Ashley John

Reputation: 2453

Either provide a public parameterless constructor on your base class or as others suggested make a call to your base class constructor by passing IEnumerable<T> from the derived class

Upvotes: 1

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

You need to inherit A<T>, not A:

public class B<T> : A<T> where T : class, new(){

}

Furthermore public A(_Data) is not constructor, which I assume you wanted. You need public A<T>(IEnumerable<T> _Data)instead.

Last but not least you have to create a constructor for B that can invoke any of those from A. So either define a parameterless constructor in A or one in B with IEnumerable<T> as argument:

public class B<T> : A<T> where T : class, new()
{
    public B<T>(IEnumerable<T> data) : base(data) { ... }
}

Upvotes: 3

Ashkan S
Ashkan S

Reputation: 11521

As it says in the error, it cannot create the base class because you did not provide the correct constructor in B. change it to this if you want to pass any args

public class B<T> : A<T> where T : class, new(){
  public B(IEnumerable<T> data):base(data) {
    }
}

Otherwise, new your data in the constructor and and pass it to base.

Upvotes: 1

Related Questions