Vahid
Vahid

Reputation: 5444

How to define derived List with methods and populate them in C#

I have the class Columns which is derived from List<Column>. I want to populate the class inside one of its methods named GetColumns(). But I'm having trouble doing this. Maybe I'm missing something very very obvious here.

What I'm trying to do is to define Collections as classes that derive from `List and I want to extend these classes to populate them and other stuff.

public class Columns : List<Column>
{        
    public void GetColumns()
    {`
        this = Building.PColumns;
    }
}

Upvotes: 0

Views: 49

Answers (3)

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

You can't assign to this in a class. (You could do so in a struct.)

Instead of:

this = Building.PColumns;

Try:

this.Clear();
this.AddRange(Building.PColumns);

Upvotes: 2

Codor
Codor

Reputation: 17595

Change the body of the method GetColumns. It is a bit unclear where Building.PColumns is defined. In neither case the this pointer can be reassigned. Furthermore, the name GetColumns suggests that something is returned. However this is not the case as its return type is void. Change the return type of GetColumns to the type of Building.PColumns and return Building.PColumns.

Upvotes: 1

Mitchell Holmans
Mitchell Holmans

Reputation: 11

If you're extending List you should just be able to call all the usual methods ie (add, addrange, remove etc..). Personally I would either extend IEnumerable or use Columns as a wrapper class with a member of type List but each to their own and it of course depends on what you're doing. Especially since you know the type of the list beforehand and you're handling the login in internal functions anyway, i would just have it as a member.

Upvotes: 1

Related Questions