In a class, you can define public instance data, as fields. Any instance of the class can read and write the instance data stored in these fields.
For example:
1
2
3
4
5
6
7
8
9
10
| public class Dog{ public string Name; public int Age;}// Creating a Dog objectDog kirby = new Dog();kirby.Name = "Kirby";kirby.Age = 14; |
You might, however, want to declare some instance data that is visible from within the class’ methods, but not visible outside the class. You can do this by declaring a field as private.
1
2
3
4
5
6
7
8
9
10
11
12
| public string Name;public int Age;private DateTime lastPrint;public void PrintName(){ Console.WriteLine(Name); // lastPrint is visible here lastPrint = DateTime.Now;} |
This private field will not be visible from outside the class.
1
2
3
4
5
| Dog kirby = new Dog();kirby.Name = "Kirby";// Compiler error: inaccessible due to its protection levelDateTime when = kirby.lastPrint; |

