Start learning free

LESSON 182 OF 347 · OBJECT-ORIENTED PROGRAMMING

Class Fields in C#: Declaring and Using Object Data

Lesson Read the full explanation

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

    C# · OBJECT-ORIENTED PROGRAMMING

    Class Fields in C#, explained

    What a field is

    An empty class makes identical objects, which isn't very useful. Real dogs have names and ages. A field is a variable that is declared inside a class and attached to the objects made from it. Every object gets its own copy of each field, so two dogs can have different names.

    Declaring fields

    A field is declared in the class body like an ordinary variable, but with an access modifier in front:

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

    Each declaration has three parts:

    • public means any code can read and write the field. A field without a modifier is private, which means only the class itself can use it. The access modifiers lesson covers that in detail.
    • The type, such as string or int, says what kind of value the field holds.
    • The name follows the type, and a semicolon ends the declaration.

    Field names written in lowercase camelCase, like name or homeTown, are a common style for public fields in teaching code. Many C# programmers prefer properties for public data, but the mechanics of fields are the same.

    Reading and writing fields

    Use the dot operator on an object to reach one of its fields:

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

    The dot belongs to a particular object. dog.age means "the age of this dog". Two objects keep separate values:

    Dog rex = new Dog();
    Dog luna = new Dog();
    rex.name = "Rex";
    luna.name = "Luna";
    // rex.name is "Rex" and luna.name is "Luna"
    

    A field can be used like any variable of its type. For example, dog.age++ increases that dog's age by one, and dog.name + "!" joins two strings.

    Default values

    Local variables must be assigned before you read them, but fields don't have that rule. If you don't assign a field, C# gives it a default value when the object is created:

    • Numeric types such as int and double start at 0.
    • bool starts as false.
    • Reference types, such as string, arrays and other classes, start as null.

    A new Dog therefore has age equal to 0 and name equal to null until you set them. A null string is not the same as an empty string "". Joining it with + treats it as empty text, so dog.name + " is " + dog.age prints " is 0" for a dog with no name, but calling a method on it, such as dog.name.ToUpper(), throws a NullReferenceException.

    You can also give a field a starting value in its declaration, which replaces the default:

    class Dog {
        public string name = "Unnamed";
        public int age;
    }
    

    Common mistakes

    • Using the class name instead of an object. Dog.name = "Rex"; doesn't compile, because name belongs to each dog, not to the class itself.
    • Forgetting public. The code compiles inside the class, but dog.name from Solution then fails with an error saying the field is inaccessible due to its protection level.
    • Declaring the field inside a method. That creates a local variable that disappears when the method ends. A field goes directly in the class body.
    • Writing the type again on assignment. string dog.name = "Rex"; is invalid. Declare the field once in the class, then assign with dog.name = "Rex";.
    • Mixing up the case. dog.Name and dog.name are different identifiers.
    • Using the wrong type. dog.age = "four"; is rejected because age is an int.

    The exercise, step by step

    The Dog class is empty at the start. The lesson's MainFunction creates a dog and prints it using dog.name and dog.age, so both fields have to exist and hold values. The expected output is:

    Rex is 4 years old
    
    1. Declare the fields inside Dog: public string name; and public int age;, one per line.
    2. Set the values in MainFunction, below the line that creates the dog: dog.name = "Rex"; and dog.age = 4;.
    class Dog {
        public string name;
        public int age;
    }
    
    class Solution {
        public void MainFunction() {
            Dog dog = new Dog();
            dog.name = "Rex";
            dog.age = 4;
            Console.WriteLine(dog.name + " is " + dog.age + " years old");
        }
    }
    

    The assignments have to come before the Console.WriteLine line. If they came after it, the line would print the default values, " is 0 years old".

    Key takeaways

    • A field is a variable inside a class; each object has its own copy.
    • Declare it with an access modifier, a type and a name.
    • Reach an object's field with the dot operator.
    • Unassigned fields get defaults: 0, false or null.
    • Fields without a modifier are private, so add public when other classes need access.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free