#231 – Declaring and Using Instance Fields in a Class
February 3, 2011 3 Comments
In a class, an instance field is a kind of class member that is a variable declared in the class and having a particular type. There is one copy of the field for each instance of the class. You can read and write the value of the field using a reference to the instance of the class.
Fields are declared in a class as follows:
public class Dog { public string Name; public int Age; }
These fields can then be used as follows:
Dog buster = new Dog(); // Create new instance of Dog buster.Name = "Buster"; // Write to Name field buster.Age = 3; // Write to Age field Dog kirby = new Dog(); // Another instance of a Dog kirby.Name = "Kirby"; kirby.Age = 13; // Reading properties int agesAdded = buster.Age + kirby.Age;
Pingback: #242 – Declaring and Using a Property in a Class « 2,000 Things You Should Know About C#
Pingback: #787 – Avoid Public Fields in a Class | 2,000 Things You Should Know About C#
Pingback: #791 – Properties Are Not Variables | 2,000 Things You Should Know About C#