Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 182 ยท Classes and Objects

Classes and Objects

Learn C# classes and objects from scratch - declaring a class, fields, methods, new, reference semantics, null, object initializers, and the difference between static and instance members.

So far you have worked with built-in types: numbers, strings, lists, dictionaries. Real programs model things from their own world: a customer, an invoice, a spaceship, a chess move. A class lets you invent a new type that bundles the data describing such a thing with the code that works on that data. An object is one actual thing built from the class, such as one particular customer.

Classes are the centre of C#. Everything in this chapter (properties, constructors, inheritance, interfaces) builds on the ideas here, so we will take it slowly: what a class is, how objects live in memory, why two variables can point at the same object, and what null really means.

A class is a blueprint, an object is a thing

Think of a class as the blueprint of a house and an object as a house built from it. One blueprint can produce many houses, each with its own paint colour and its own people inside.

C#
class Dog
{
    public string Name = "";
    public int Age;

    public void Bark()
    {
        Console.WriteLine($"{Name} says woof!");
    }
}

The class Dog declares two fields (variables that belong to each dog) and one method (code that a dog can run). Nothing exists yet. We have only described what a dog is. To get an actual dog you use the new keyword.

C# Your first class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both dogs share the same code, but each has its own Name and Age. When rex.Bark() runs, Name inside the method means "the name of the dog I was called on". The dot (.) is how you reach into an object.

Type declarations in a file that uses top-level statements must appear after all the statements, otherwise the compiler reports error CS8803. In a real project each class normally lives in its own file, so this ordering rule only matters in small demos like the ones in this course.

Fields, methods and access

A class body can contain:

  • Fields: variables that store the state of an object.
  • Methods: functions that act on that state.
  • Properties, constructors, events and more, which come in the next lessons.

The word public in front of each member is an access modifier. It says "code outside the class may use this". Without a modifier, class members are private by default and only the class itself can touch them. We will study these rules in Access Modifiers and Encapsulation. For now, remember that making a field public is fine in a short demo, but in real code you will usually keep fields private and expose properties instead.

Fields get a default value if you do not set one: 0 for numbers, false for bool, and null for reference types such as string. Because this project has nullable reference types on, the compiler warns you when a non-nullable string field could stay null. That is why Name above is initialized to "".

Reference semantics: two names, one object

This is the most important idea in the lesson. A variable of a class type does not hold the object itself. It holds a reference to it, like a slip of paper with an address on it. The object lives elsewhere (on the managed heap), and the variable only knows where.

Copying a variable therefore copies the slip of paper, not the house.

C# Two variables, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Changing Value through second also changed what first sees, because both names point at the same object. third has an equal value but is a different object. This is why the == operator on a plain class compares identity (are these the same object?), not contents. We return to this in The object Class: Equals, GetHashCode and ToString.

The same effect happens when you pass an object to a method: the method receives a copy of the reference, so it can change the caller's object. Compare this with int or struct values, which are copied whole. The difference is explained in Value and Reference Types.

Where objects live

Objects created with new live on the managed heap. The garbage collector (GC) frees an object automatically once nothing refers to it any more. You never write delete. When first, second and every other reference to an object are gone or out of scope, the memory becomes eligible for cleanup. You do not control exactly when it happens, which is why resources such as files need IDisposable rather than relying on the GC.

null: a reference to nothing

A reference variable may hold the special value null, meaning "no object". Calling a method or reading a field through null throws a NullReferenceException, the most common runtime error in C# history.

Modern C# helps you avoid it. With nullable reference types enabled, a type written Dog promises "never null", and Dog? says "might be null". The compiler tracks this and warns you before the program runs.

C# null and the null-conditional operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use is null and is not null for checks, and ?. and ?? to handle absence gracefully. The next chapters go deeper in Nullable Reference Types and Null-Handling Operators.

Object initializers

Writing rex.Name = "Rex"; rex.Age = 4; on separate lines gets tedious. An object initializer sets members right after new, in braces:

C# Object initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

new() without a type name is called target-typed new (C# 9). When the compiler already knows the type from the left-hand side, you can leave it out. Object initializers work with fields and with properties, and Constructors and Object Initialization explains exactly what they do under the hood.

Static versus instance members

Everything so far was instance state: each dog has its own Name. Sometimes a value belongs to the class as a whole. Marking a member static makes it exist once, no matter how many objects you create, and you reach it through the class name.

C# Instance vs static

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A static method has no "current object", so it cannot use instance fields directly (it would not know whose Name). Static members get a full lesson of their own: Static Members and Static Classes.

Designing a good class

A class should represent one idea and keep its data and the code that works on that data together. A few habits will serve you for years:

  • Name classes with nouns in PascalCase: Invoice, ShoppingCart, EmailAddress.
  • Keep data private and expose carefully chosen behaviour.
  • Make invalid states impossible if you can. A BankAccount that can have a negative balance by accident is a bug waiting to happen.
  • Prefer small classes. If a class needs the words "And" or "Manager" in its name, it probably does too much.
  • Do not use a class when a record or struct fits better. A pure data holder with value-based equality is often a record, and a tiny immutable value such as a coordinate is often a struct.

Here is a slightly richer example with behaviour that protects the data.

C# A small BankAccount class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Outside code cannot set the balance to a nonsense value; the only way in is through Deposit and Withdraw, which enforce the rules. That idea, called encapsulation, is the real reason to use classes. (The Owner and Balance members are properties, covered in the next lesson.)

Common mistakes

  • Forgetting new. Dog d; declares a variable but creates no object. Using it before assigning gives compiler error CS0165 ("use of unassigned local variable").
  • Assuming assignment copies an object. b = a copies the reference only. To make an independent copy you must create a new object.
  • Calling a method on null. Turn on nullable reference types, listen to the warnings, and prefer ?. where absence is expected.
  • Making everything public. It is quick, but it lets any code break your object's rules.
  • Comparing objects with == and expecting equal contents. For a plain class that checks identity.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between a class and an object?

    The class describes the members; each new expression builds a separate object with its own field values.
  2. 2. After Counter b = a; (where a is a Counter), what happens when you change b.Value?

    Class variables hold references. Assignment copies the reference, so both names point to one object.
  3. 3. What does person?.Name do when person is null?

    The null-conditional operator stops evaluating and produces null when the left side is null.
  4. 4. Where does a static field live?

    A static member belongs to the type itself, so there is exactly one copy no matter how many objects exist.
  5. 5. What does Dog d = new() { Name = "Rex" }; use?

    new() lets the compiler infer the type from the declaration, and the braces set members right after construction.

Summary

  • A class defines fields and methods; an object is one instance made with new.
  • Class variables hold references. Assignment copies the reference, so two variables can share one object.
  • null means "no object"; use nullable annotations, is null, ?. and ?? to deal with it safely.
  • Object initializers (new Dog { Name = "Rex" }) and target-typed new (new()) make creation concise.
  • Static members belong to the class once; instance members belong to each object.
  • Keep data private and let methods enforce the rules.

Next: Properties