Ryan Callahan
Ryan Callahan

Reputation: 115

Is there a way to use parameters with accessors in c#

I really like the syntax for accessors in c#, but I need to use some extra values in my setters for a few properties.

Is there any way I can do something similar to this or is it not possible with this type of syntax?

public class Accesssor{
    public List<CustomObject> AccessorStuff { 
        get {
                return AccessorStuff;
            } 
        set (ExtraParameters????) => {
                AccessorStuff.add(new CustomObject(value,ExtraParameters))
            }
        }
}

(I'm also finding this hard to search for because I don't know if this has an exact name, so if I could also get that piece of information I would massively appreciate it)

Thank you in advance.

Upvotes: 1

Views: 579

Answers (2)

Tomer
Tomer

Reputation: 1704

No, this is not possible - and not what I'd expect if I used your property. When I use set I expect to change the List, not add values to it. This is most commonly achieved via class methods:

public void AddObject(CustomObjectType obj, ExtraParameters extraParameters) => 
    AccessorStuff.Add(new CustomObject(obj, ExtraParameters));

Upvotes: 6

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112362

You can use a so called indexer in C#

public List<CustomObject> this[int index]
{
    get { /* return the specified index here */ }
    set { /* set the specified index to value here */ }
}

You can then access it with

obj[5] = someValue;
var result = obj[0];

Exactly as with methods, you can have any number of parameters (but at least one) of any type in indexers. You can also overload the indexer, i.e. have different versions with a different number of parameters or different parameter types. E.g.:

public List<CustomObject> this[string name]
{
    ...
}

public List<CustomObject> this[string name, bool caseSensitive]
{
    ...
}

But in any case the index applies to the setter as well as to the getter. Other than with properties, indexers cannot be named. If you need serveral such "properties" with parameters, just use plain old methods.

public void SetProperty(Extra stuff...)
{
    ...
}

Upvotes: 3

Related Questions