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.Col
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>();
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;
}
}
I think you have yourself a bit mixed up here.
The type of Packages is List<Package>
. When you're calling packages.Add(value);
, packages
is in fact, List<Package>
.
public List <Package> Packages
{
get { return packages; }
set { packages = value; }
}
This corrects the property.
To add an item:
Packages.Add(myPackage);
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.
You are trying to use the set{}
method as the Add
method, which it isn't. set
is used to change the entire collection whereas an Add
method would add an item to the collection. what has been stated in other answers is correct... if you really want the =
operator to add to the collection rather than assign a new collection, you can use AddRange()
but for clarity sake, you should be overriding the =
operator if that is the case.
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; }