Item 1: Use Properties Instead of Accessible Data Members(Effective C#)
You can specify different accessibility modifiers to the get and set accessors in a property in C#.
Indexers can be virtual or abstract; indexers can have separate access restrictions for setters and getters. You cannot create implicit indexers as you can with properties.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace EffectiveCSharpItem1
7 {
8 public class Person
9 {
10 private string name;
11 private List<string> friends = new List<string>();
12
13 public string Name
14 {
15 get
16 {
17 return name;
18 }
19 protected set
20 {
21 this.name = value;
22 }
23 }
24
25 public override string ToString()
26 {
27 return this.name;
28 }
29
30 public string this[int index]
31 {
32 get { return friends[index]; }
33 set { friends[index] = value; }
34 }
35
36 public Person(string name)
37 {
38 this.Name = name;
39 friends.Add("Summer");
40 }
41 }
42
43 class Program
44 {
45 static void Main(string[] args)
46 {
47 Person p = new Person("Ray");
48 Console.WriteLine(p.ToString());
49 Console.WriteLine(p[0]);
50
51 Console.Read();
52 }
53 }
54 }
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace EffectiveCSharpItem1
7 {
8 public class Person
9 {
10 private string name;
11 private List<string> friends = new List<string>();
12
13 public string Name
14 {
15 get
16 {
17 return name;
18 }
19 protected set
20 {
21 this.name = value;
22 }
23 }
24
25 public override string ToString()
26 {
27 return this.name;
28 }
29
30 public string this[int index]
31 {
32 get { return friends[index]; }
33 set { friends[index] = value; }
34 }
35
36 public Person(string name)
37 {
38 this.Name = name;
39 friends.Add("Summer");
40 }
41 }
42
43 class Program
44 {
45 static void Main(string[] args)
46 {
47 Person p = new Person("Ray");
48 Console.WriteLine(p.ToString());
49 Console.WriteLine(p[0]);
50
51 Console.Read();
52 }
53 }
54 }