Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass an argument to a setter

Tags:

c#

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

like image 364
user565660 Avatar asked May 25 '11 12:05

user565660


2 Answers

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"
like image 110
Jon Skeet Avatar answered Sep 20 '22 06:09

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)

like image 30
Colin Mackay Avatar answered Sep 23 '22 06:09

Colin Mackay