Is there a way to pass an argument to a setter? How would I pass a string into the setter below? How would I call the setter with the new string param?
public string It
{
get{ { return it;}
set { it = value;}
}
Thank you very much
The setter gets value
as its own "argument", based on the value you assign to the property:
foo.It = "xyz"; // Within the setter, the "value" variable will be "xyz"
If you want to use an extra parameter, you need an indexer:
public string this[string key]
{
get { /* Use key here */ }
set { /* Use key and value here */ }
}
You'd then access it as
foo["key"] = "newValue";
You can't give indexers names in C#, or use named indexers from other languages by name (except in the case of COM, as of C# 4).
EDIT: As noted by Colin, you should use indexers carefully... don't just use them as a way of getting an extra parameter just for the setter, which you then ignore in the getter, for example. Something like this would be terrible:
// Bad code! Do not use!
private string fullName;
public string this[string firstName]
{
get { return fullName; }
set { fullName = firstName + " " + value; }
}
// Sample usage...
foo["Jon"] = "Skeet";
string name = foo["Bar"]; // name is now "Jon Skeet"
You can assign it like you can assign a value to a variable:
It = "My String";
Property getters/setters are just syntactic sugar for string get_It()
and void set_It(string value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With