Tools
Log in
English

Learn to codeC#

C# classes and objects

Based on C# 12new() · C# 9+

C# classes, constructors, this, object initializers and new(), step by step.

In one line

A class bundles values (fields and properties) and actions (methods) into a template; an object is one real bundle of values made from it with new.

Why you need it

Carrying the names and songs of two playlists in loose variables soon gives you name1, songs1, name2, songs2. Every new playlist means edits in more places.

Put the name, the song list, Add and Summary in one Playlist class and each playlist becomes one variable. A third one is a single new Playlist("Study") line.

Everyday picture

Think of a rubber stamp and the paper it marks. There is one stamp (the class), but you can press it on as many sheets (objects) as you like and write something different on each. The constructor is the press itself; an object initializer is the note you add right after pressing.

Example code

Program.cs · 43 lines
var road = new Playlist("Road trip");road.Add(new Song("Sunrise", 214));road.Add(new Song("Highway", 187) { Liked = true });Playlist calm = new("Calm");calm.Add(new Song("Rain", 245));Console.WriteLine(road.Summary());Console.WriteLine(calm.Summary()); class Song{    public string Title { get; }    public int Seconds { get; }    public bool Liked { get; set; }     public Song(string title, int seconds)    {        Title = title;        Seconds = seconds;    }} class Playlist{    private readonly string name;    private readonly List<Song> songs = new();     public Playlist(string name)    {        this.name = name;    }     public void Add(Song song)    {        songs.Add(song);    }     public string Summary()    {        int total = songs.Sum(s => s.Seconds);        int liked = songs.Count(s => s.Liked);        return $"{name}: {songs.Count} songs, {total / 60}m {total % 60}s, {liked} liked";    }}

When to use it

  • Many records share one shape (songs, members, orders, bookings)
  • Values and the code that works on them belong together (add a song, total the length)
  • A noun keeps coming up when you describe the program. That noun is a class candidate.

A small type that only carries two or three values can be one line: record Point(int X, int Y);. Records come back in the composition and static topic.

With the type on the left, as in List<Song> songs = new();, you can drop the type name after new (C# 9+).

Common mistakes

Declaring a variable without creating an object

Playlist list; only makes a slot for an object. Until you put an object in it with new, you cannot use it, and the compiler says so.

Wrong

Playlist list;list.Add(new Song("Rain", 245));

What the C# compiler sayserror CS0165: Use of unassigned local variable 'list'

Fixed

Playlist list = new("Calm");list.Add(new Song("Rain", 245));Console.WriteLine(list.Summary());

When you run itCalm: 1 songs, 4m 5s, 0 liked

Using a variable that may be null

Song? says the value may be null. The compiler warns (CS8602) but still builds, and the program stops with a NullReferenceException. Use ?. and ?? to decide what happens when it is null.

Wrong

Song? pick = null;Console.WriteLine(pick.Title);

When you run itUnhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

Fixed

Song? pick = null;Console.WriteLine(pick?.Title ?? "(nothing picked)");

When you run it(nothing picked)

Treating a struct like a class

A struct is a value type, so var b = a; copies the whole thing. Changing b leaves a at 0. If both names should point to one object, make it a class, which is a reference type.

Wrong

var a = new Counter();var b = a;b.Add();Console.WriteLine(a.Value); struct Counter{    public int Value { get; private set; }     public void Add() => Value++;}

When you run it0

Fixed

var a = new Counter();var b = a;b.Add();Console.WriteLine(a.Value); class Counter{    public int Value { get; private set; }     public void Add() => Value++;}

When you run it1

Check yourself

Question 1

A song is added only to a. What does b.Summary() print?

var a = new Playlist("A");var b = new Playlist("B");a.Add(new Song("One", 100));Console.WriteLine(b.Summary());

Show the answer

Answer: 2. B: 0 songs, 0m 0s, 0 liked a and b are separate objects with their own lists. a.Add changes only the list of a.

Question 2

{ Liked = true } follows the constructor call. What is printed?

var s = new Song("Wind", 90) { Liked = true };Console.WriteLine(s.Liked);

Show the answer

Answer: 1. True The object initializer runs right after the constructor, so Liked is true. C# prints a bool with a capital letter, as True.

Questions people ask

How is a constructor different from an object initializer { }?

A constructor takes the values an object must have and sets it up. The { Liked = true } block after it is a short way to fill settable or init properties once the constructor has finished.

Are new Playlist(...) and new(...) the same?

They create the same object. With the type written on the left you may drop it on the right and write new(...) (C# 9+). With var on the left, the type name is required.

Should I use class or struct?

Almost always class. A struct suits small values that are copied whole on assignment, such as a point or a color. When unsure, start with class.