Kourosh
Kourosh

Reputation: 618

Constructor for a subclass of List<T> C#

This is my class:

public class CustomList: List<SomeType>{

 SomeType myList;

 public CustomList(List<SomeType> list){
  myList = list;
 }

//some methods
}

and I initialise it like this:

CustomList myCustomList = new CustomList(someList);

However upon accessing the first member of the list (myCustomList[0]) i get: AurgumentOutOfRangeException error.

Am I doing anything wrong in my custom list constructor and/or initialisation?

Appreciate your help.

Edit:

SomeType is a class consist of some public variables:

public class SomeType{
 public string title;
 public string campaign;
}

Upvotes: 0

Views: 175

Answers (1)

Sam Axe
Sam Axe

Reputation: 33738

I assume you want the .ctor argument to be added to the list. So add it...

public class CustomList: List<SomeType>{

 public CustomList(List<SomeType> list){
  this.AddRange(list);
 }

//some methods
}

As Alexei pointed out in the comments an alternative method of calling the base class .ctor using this syntax in C#:

public class CustomList : List<SomeType> {
    public CustomList(List<SomeType> list) : base(list) { ... }
}

Upvotes: 4

Related Questions