Classes

A class and its instances

A class is a type that holds data and the methods that work on it. The data lives in fields, each instance has its own copy, and new creates an instance. The class in the first program keeps one number private and offers a property to read it and two methods to change it:

var first = new Counter(); var second = new Counter(); first.Increment(); first.Increment(); second.Increment(); Console.WriteLine($"first {first.Value} second {second.Value}"); class Counter { private int value; public int Value => value; public void Increment() { value++; } public void Reset() { value = 0; } }

dotnet run

first 2 second 1

Two instances, two fields: the two increments went into the first object and the one into the second. The property Value is expression-bodied, => value is the body of a getter that reads the field, and Reset is there to show that a class may have a method nobody calls yet without any warning.

A variable holds a reference

new puts the object on the heap and gives back a reference, which is what the variable stores. Assigning a class variable to another one copies the reference, not the object:

var first = new Counter(); first.Increment(); var second = first; second.Increment(); Console.WriteLine($"first {first.Value} second {second.Value} same {ReferenceEquals(first, second)}"); class Counter { private int value; public int Value => value; public void Increment() { value++; } }

dotnet run

first 2 second 2 same True

There is one object and two names for it, which ReferenceEquals confirms. The lesson on value and reference types measures the same assignment on a struct, where the copy is the whole object and the two variables part ways after it.

Access modifiers

private is the default for a field and internal the default for a class; the course writes both out. A member marked private is visible only inside its type, and the compiler says so with a real diagnostic:

var counter = new Counter(); counter.Increment(); Console.WriteLine(counter.value); Console.WriteLine(counter.Value); class Counter { private int value; public int Value => value; public void Increment() { value++; } }

dotnet build

Program.cs(3,27): error CS0122: 'Counter.value' is inaccessible due to its protection level

Build FAILED.

Program.cs(3,27): error CS0122: 'Counter.value' is inaccessible due to its protection level
0 Warning(s)
1 Error(s)

Time Elapsed 00:00:04.49

The position is the name in the call, not the declaration, which is the useful part: the compiler points at the place that broke the rule. The property on the next line is fine, and it is the reason the field can stay private: the class decides what a reader may do with the number.

The four modifiers a beginner meets are private (this type only), protected (this type and its subclasses), internal (this assembly) and public (everyone). A member with no keyword is private inside a class and public on an interface, which is why writing the keyword is the safer habit.

this and the type

Inside an instance method, this names the object the method runs on. It is needed when a parameter has the same name as a field, when one constructor calls another, and when an object passes itself to something else; in a plain method it is optional and the course leaves it out.

var counter = new Counter(); counter.Increment(); Console.WriteLine(counter.Describe()); Console.WriteLine($"same class: {typeof(Counter).Name}"); class Counter { private int value; public int Value => value; public void Increment() { value++; } public string Describe() => $"{this.GetType().Name} at {this.value}"; }

dotnet run

Counter at 1
same class: Counter

GetType() is inherited from System.Object, the root of every type, and typeof(Counter) is the same type object obtained from the name. Both print Counter, and the page on GetType goes further into what a type object can be asked.

Exercises

  1. Add a Decrement method to the first program and make it refuse to go below zero.
  2. Change private int value to public int value and watch the CS0122 go away. Which other name could you give the field to keep it private and still read it?
  3. Give the class a second field and a method that returns both values as a tuple.
  4. Make two variables point at one object, then reassign one of them to a new object. What does the other variable see?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does new Counter() return?

    Answer

    A reference to a new object on the heap

    A class is a reference type, so new allocates the object and yields a reference to it.

  2. Two variables are assigned the same class instance. What can they change?

    Answer

    The same object, because both hold the same reference

    Assignment of a reference type copies the reference, so both names reach one object.

  3. What does this program print? var a = new Box(); var b = new Box(); a.N = 3; b.N = 4; Console.WriteLine(a.N + b.N); class Box { public int N; }

    Answer

    7

    Each new object has its own field, so the two numbers are 3 and 4 and their sum is 7.

  4. What does CS0122 mean?

    Answer

    A member is inaccessible due to its protection level

    The error names the member and the access level that blocked the use.

  5. What is the default access level of a field declared without a keyword?

    Answer

    private

    Inside a class a member with no modifier is private; a top-level class is internal.

  6. What does public int Value => value; declare?

    Answer

    A read-only property whose getter returns the field

    The arrow is the body of the getter, so the property has no setter and cannot be assigned.

  7. What does this name inside an instance method?

    Answer

    The object the method was called on

    this is the current instance; a static method has no this.

  8. What does this program print? var c = new Counter(); c.Add(); var d = c; d.Add(); Console.WriteLine(c.N); class Counter { public int N; public void Add() => N++; }

    Answer

    2

    c and d name one object, so both calls increment the same field.

  9. Which is a reason to keep a field private and expose a property?

    Answer

    The class decides how the value may be read or changed

    A property is a place to validate, compute or later change the representation without breaking callers.

  10. Where does an object created with new live?

    Answer

    On the heap, managed by the garbage collector

    A class instance is a heap object, and the GC frees it when no reference is left.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image