1

For the following code, I don't quiet understand what is the meaning of "{0}" presented in both getter and setter, I know it is referring to a index number but why it should be 0 ? I'm also confused about the variable "value". Is this just a place parameter like we used in Java ?

Thank you.

void Main() {
Button b = new Button();  
b.Caption = "abc";
string c = b.Caption; 
Console.WriteLine("c = {0}\r\n", c);

Button p = new Button{Caption = "cool"};    
string e = p.Caption;
Console.WriteLine("e = {0}", e);
}

class Button {
    private string caption;
    public string Caption {
        get {
            Console.WriteLine("get {0}", caption);
            return caption;
 }
    set {
        Console.WriteLine("set {0}", value);
        caption = value;
    }
  } 
}
Phantom
  • 443
  • 1
  • 5
  • 15

2 Answers2

2

It's a format placeholder, the actual method Console.WriteLine() allows you to use the same syntax as String.Format().

The placeholders represent the numeric indice of the parameters supplied after the format string.

For example:

var s = String.Format("Hello {0}!", "World");

Would print:

Hello World!

An example of multiple placeholders would be:

var s = String.Format("{0} Blind {1}", "Three", "Mice");

You can also then use various other formatting specifiers to finer control the output of the value. It's quite a broad topic so see here on MSDN for more information on Composite Formatting.

As to value that's a contextual keyword, i.e it only exists within certain contexts, in your case properties.

value acts in this instance as a variable of the property type filled with the value of the property being set.

You can read more about contextual keywords again on MSDN here.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
0

{0}, means take the 1st of the objects specified after the format string

{1}, means take the 2nd of the objects specified after the format string etc

...in other words...the index is zero based.

The "value" keyword is a "contextual keyword" is it a placeholder to represent the actual value "set" to the property (when used in a propert setter).

(there are other ones available in case you are interested: https://msdn.microsoft.com/en-us/library/the35c6y.aspx)

Colin Smith
  • 12,375
  • 4
  • 39
  • 47