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.
C# code does not run on this page. Run your edited code on your own computer with dotnet run.
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(newSong("Rain", 245));
What the C# compiler sayserror CS0165: Use of unassigned local variable 'list'
Fixed
Playlist list = new("Calm");list.Add(newSong("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.
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 = newCounter();var b = a;b.Add();Console.WriteLine(a.Value);structCounter{publicintValue { get; privateset; }publicvoidAdd() => Value++;}
When you run it0
Fixed
var a = newCounter();var b = a;b.Add();Console.WriteLine(a.Value);classCounter{publicintValue { get; privateset; }publicvoidAdd() => Value++;}
When you run it1
Check yourself
Question 1
A song is added only to a. What does b.Summary() print?
var a = newPlaylist("A");var b = newPlaylist("B");a.Add(newSong("One", 100));Console.WriteLine(b.Summary());
Show the answer
Answer: 2. B: 0 songs, 0m 0s, 0 likeda 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 = newSong("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.