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:
publicmeans any code can read and write the field. A field without a modifier isprivate, which means only the class itself can use it. The access modifiers lesson covers that in detail.- The type, such as
stringorint, 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
intanddoublestart at0. boolstarts asfalse.- Reference types, such as
string, arrays and other classes, start asnull.
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, becausenamebelongs to each dog, not to the class itself. - Forgetting
public. The code compiles inside the class, butdog.namefromSolutionthen 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 withdog.name = "Rex";. - Mixing up the case.
dog.Nameanddog.nameare different identifiers. - Using the wrong type.
dog.age = "four";is rejected becauseageis anint.
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
- Declare the fields inside
Dog:public string name;andpublic int age;, one per line. - Set the values in
MainFunction, below the line that creates the dog:dog.name = "Rex";anddog.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,falseornull. - Fields without a modifier are private, so add
publicwhen other classes need access.