#231 – Declaring and Using Instance Fields in a Class

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;
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #231 – Declaring and Using Instance Fields in a Class

  1. Pingback: #242 – Declaring and Using a Property in a Class « 2,000 Things You Should Know About C#

  2. Pingback: #787 – Avoid Public Fields in a Class | 2,000 Things You Should Know About C#

  3. Pingback: #791 – Properties Are Not Variables | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: