Start learning free

LESSON 286 OF 674 · FUNCTIONS & CLASSES

Class Fields in C#

Lesson

TL ; DR:

  • A field is a variable that lives inside a class. Each object of that class has its own copy.


  • Declare a field by giving it a type and a name, with public in front so other code can read and write it:

    class Dog {
        public string name;
        public int age;
    }
    

  • Access a field on an object with the dot operator: dog.name = "Rex";



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical to every other one. That's not very useful. Real dogs have names, ages, breeds. We need a way to attach data to each object.

That's what fields are for. A field is a variable that belongs to a class — and each object created from that class gets its own copy of every field.


Declaring fields

You declare a field inside the class body, just like a regular variable, but with an access modifier in front:

class Dog {
    public string name;
    public int age;
}

Two pieces here:

  • public means "any code can read and write this field". You'll see private later for fields that should only be touched by the class itself.

  • string name; is just a variable declaration — the same syntax you'd use anywhere else. Type, then name, then semicolon.


Reading and writing fields

Once you have an object, use the dot operator . to get to its fields:

Dog dog = new Dog();
dog.name = "Rex";        // write
dog.age = 4;
Console.WriteLine(dog.name);   // read → prints "Rex"

Each object has its own slot for every field, so two dogs can have different names:

Dog rex = new Dog();
Dog luna = new Dog();
rex.name = "Rex";
luna.name = "Luna";
// rex.name is "Rex", luna.name is "Luna" — they don't interfere.

Default values

If you don't assign a field, C# fills it in for you with a sensible default:

  • Numbers default to 0

  • bool defaults to false

  • Reference types (string, arrays, other classes) default to null

So a freshly-made Dog has age = 0 and name = null until you set them.


Your task

Update the Dog class to have two fields: name (a string) and age (an int). Then in MainFunction, set them on the dog object so the pre-filled Console.WriteLine prints:

Rex is 4 years old
STEP 1 OF 2
    Ctrl + Enter to check