C# Classes and Objects
A class defines a new type: what data its objects hold (fields and properties) and what they can do (methods). An object is a specific instance of that class, created with the new keyword.
Defining a class
using System;
class Program
{
static void Main()
{
Book b = new Book();
b.Title = "Dune";
b.Author = "Frank Herbert";
b.Pages = 412;
Console.WriteLine(b.Title);
Console.WriteLine(b.Describe());
}
}
class Book
{
public string Title;
public string Author;
public int Pages;
public string Describe()
{
return quot;'{Title}' by {Author}, {Pages} pages";
}
}Dune
'Dune' by Frank Herbert, 412 pages
class Book { … }declares the type.Title,AuthorandPagesare fields — variables that belong to each object.Describe()is an instance method: it can use the fields of the object it is called on.publicmakes these members accessible from outside the class (more in the Access Modifiers lesson).new Book()allocates a new object; the dot operatorb.Titleaccesses its members.
Multiple objects
Every object has its own copy of the fields. Changing one object does not affect another.
using System;
class Program
{
static void Main()
{
var a = new Counter();
var b = new Counter();
a.Increment();
a.Increment();
b.Increment();
Console.WriteLine(quot;a = {a.Value}");
Console.WriteLine(quot;b = {b.Value}");
}
}
class Counter
{
public int Value;
public void Increment() => Value++;
}a = 2
b = 1
Fields that you do not set get their default value (0 for Value here), just like array elements.
Object initializers
Instead of setting fields one statement at a time, you can use an object initializer — braces after new with Member = value pairs:
using System;
using System.Collections.Generic;
var library = new List<Book>
{
new Book { Title = "Emma", Author = "Jane Austen", Pages = 474 },
new Book { Title = "Ulysses", Author = "James Joyce", Pages = 730 },
};
foreach (var book in library)
Console.WriteLine(book.Describe());
class Book
{
public string Title = "";
public string Author = "";
public int Pages;
public string Describe() => quot;{Title} ({Author}) - {Pages} p.";
}Emma (Jane Austen) - 474 p.
Ulysses (James Joyce) - 730 p.
You can also write Book b = new(); — the target-typed new — when the type is already stated on the left.
Classes are reference types
A class variable holds a reference to an object, not the object itself. Assigning one variable to another copies the reference, so both refer to the same object:
using System;
class Program
{
static void Main()
{
var p1 = new Point { X = 1, Y = 2 };
var p2 = p1; // same object
p2.X = 100;
Console.WriteLine(p1.X);
var p3 = new Point { X = 1, Y = 2 };
Console.WriteLine(p1 == p2); // same reference
Console.WriteLine(p1 == p3); // different objects
Point nothing = null;
Console.WriteLine(nothing == null);
}
}
class Point
{
public int X;
public int Y;
}100
True
False
True
A variable that refers to no object holds null. Calling a method on null throws a NullReferenceException — the Nullable Types lesson shows how C# helps you avoid that.
The ToString method
Every class inherits a ToString() method from System.Object. By default it returns the type name; override it to get a useful text representation, which Console.WriteLine and string interpolation then use automatically:
using System;
var t = new Temperature { Celsius = 21.5 };
Console.WriteLine(t);
Console.WriteLine(quot;Today: {t}");
class Temperature
{
public double Celsius;
public override string ToString() => quot;{Celsius:F1}°C";
}21.5°C
Today: 21.5°C
Tip: Put each public class in its own file named after the class (
Book.cs,Counter.cs). In our single-file playgrounds we keep everything together.
Test yourself
Which keyword creates a new object?
- class
- new
- create
- object
After var a = new Point(); var b = a; b.X = 5;, what is a.X?
- 0
- 5
- null
- It does not compile
What does Console.WriteLine(obj) print if the class does not override ToString?
- The field values
- An empty line
- The type's full name
- null