Defining classes
Learn to define classes with the class keyword and instantiate with new.
Defining a class
A class is a template used to create objects. In C# a class starts with the class keyword, followed by a name and a body in curly braces.
Example: class Book { }. Here Book is the class name; the body is empty for now. Class names use PascalCase: UserAccount, ShoppingCart. Defining a class does not run it; it only prepares the template. To use the template you create an instance with new.
Creating instances with new
To create an object from a class you use the new keyword. new allocates memory, calls the constructor and returns a reference to the new object.
Example: Book book = new Book();. The left side declares that the book variable is of type Book; the right side creates a new Book object. The parentheses are the constructor call. Now book holds a reference to that object.
Exercise Define the Book class and create an instance
Define a Book class with an empty body. Inside Main create an instance with new Book() and print "Book created" with Console.WriteLine.
Show example solution
Define the class with class Book { }. In Main add Book book = new Book(); and Console.WriteLine("Book created");.
Example solution:
using System;
class Book
{
}
class Program
{
static void Main()
{
Book book = new Book();
Console.WriteLine("Book created");
}
}
Test yourself
-
Which is a valid class definition?
- Book class { }
- function Book() { }
- class Book { }
- class Book()
Show answer
class Book { } — Correct. The class keyword comes first, then the name and curly braces.
-
Write the new keyword
Book book = ____ Book();Show answer
Book book = new Book(); -
Match each keyword to its meaning
- class
- Class template
- new
- Creates an instance
- void
- No return value
- public
- Access from anywhere