Setting List items in C# without automatic setter/getter

23,356

Solution 1

Your code should look like this.

private var packages = new List<Package>();    

public List<Package> Packages
{
    set { packages = value; }
    get { return packages; }
}

If you're trying to use the index getter/setter for some kind of passthrough:

public int this[int key]
{
    get
    {
        return Packages[key];
    }
    set
    {
        Packages[key] = value;
    }
}

Solution 2

With a getter/setter the input and output types must be the same. (hence the declaration being public List<Package> Packages { ... - it is expecting an input of List<Packages> and an output of List<Packages>.

What you are doing here is trying to get type List<Package> and set type Package. This is not allowed.

What I think you want to do is the following:

private List<Package> packages = new List<Package>();    

public List<Package> Packages
{
    // no setter
    get { return packages; }
}

Then call myObject.Packages to get all the packages and myObject.Packages.Add(package) to add.

Solution 3

If you really want to add value, which is a List<Package>, to packages you should use

set { packages.AddRange(value); }

Otherwise,

set { packages = value; }

Solution 4

You can not do that.

if you are trying to set an element you should...

public void addPackage(Package pack){
    packages.Add(pack);
}

usage: MyClass m= new MyClass(); m.addPackage(new Package());

if you are trying to set the collection then ...

public List<Package> Packages
{
    set { packages=value; }
    get { return packages; }
}

usage:

MyClass m= new MyClass();
m.Packages=new List<Package>();
Share:
23,356
Mads K
Author by

Mads K

Updated on July 05, 2022

Comments

  • Mads K
    Mads K almost 2 years

    I'm trying to make a manual setter/getter method in C#, but i'm getting the following error from the "set"-line: Error: The best overloaded method match for 'System.Collections.Generic.ListPackage.Add(Package)' has some invalid arguments

    private List<Package> packages = new List<Package>();    
    
    public List<Package> Packages
    {
        set { packages.Add(value); }
        get { return packages; }
    }