Skip to content

C# Adventure 05: Classes and Objects

In this section of the Adventure Game series we'll re-conceptualize our existing code as classes. We'll also talk about how C# is an object-oriented language and how to create custom classes for our application.

Classes and Objects

Object-oriented programming models a problem by organizing it as a collection of discrete objects. Classes are defined that serve as templates for objects that have common attributes and/or behaviors. Objects are instances of a class. You can make several objects from a class, and each can have unique information.

The relationship between a class and objects that are instances of the class is like the relationship between a recipe and cookies. The recipe and the cookie are not the same thing. Using the recipe, you can make lots of cookies. You can even individually decorate each cookie so that it looks unique. Each cookie will have common attributes that are defined by the recipe.

classes and objects

Just like the recipe and a cookie made from the recipe are not the same thing, a class and an object are not the same, either.

Another example is a blueprint for a birdhouse. If you have a blueprint, you can make a lot of birdhouses. You can even customize each if you'd like, but they will all share elements that make them houses for birds. The blueprint and the resulting houses are not the same thing.

Static

The keyword static allows a member of a class to be used without creating an instance of the class first. We've used classes in our code but we haven't created any objects yet. We'll walk through how to do that when we add code to our Item class.

OO is a complex idea. Don't worry if you aren't comfortable with it right away. After you make a few applications with custom classes it will make more sense.

OO and C#

C# is an object-oriented programming language. In the simple code we have, you can already see how OO is integrated with C#:

using System;

namespace Adventure
{
    class Program
    {
        static void Main()
        {
            string CharacterName = "John Doe";

            Console.WriteLine("Game Title");
            Console.WriteLine("Welcome to ...");
            Console.WriteLine("What would you like your character's name to be?");
            CharacterName = Console.ReadLine();

            Console.WriteLine("Your character is now named " + CharacterName + "!");
            Console.ReadKey();
        }
    }
}

Visual Studio's default template created a class for us: Program. The class has one method: Main().

Diagramming the class in UML would look like this:

Program
[no attributes]
Main()

All of the statements for our application are currently in Main(), the entry point for the application. It is a best practice to keep the code in Main() at a minimum, plus it will give us more options on how we can structure what we are building.

Let's restructure what we've written with custom classes.

Quick Quiz

C# is an object-oriented programming language.

Correct
Incorrect

Main() is the default entry point for a C# application.

Correct
Incorrect

Class Creation

How you model your class depends on how you conceptualize your application. There is no one "right" way to build a class; as long as you are following the language's rules you have a lot of freedom in expression.

Here is one way in which we could organize our Adventure Game code:

  • Program: The base class for our application that has the entry point, Main().
  • Game: A general class that will store data about the current game being played. We won't create instances of this class, so we will make it static.
  • Item: A class that we will make instances of to create unique items the player can interact with.

The two new classes can be diagrammed with placeholders for now:

Game
(attributes will be here)
(behaviors will be here)
Item
(attributes will be here)
(behaviors will be here)

We could break our game down even further with classes for characters and other game elements. We'll stay with this simple structure, though, for this beginning game.

Shared Namespace

All three of our classes will be in the same namespace, Adventure. Imagine our Adventure namespace as a container with three smaller containers (our three classes) nested inside. Each class is itself a container for its attributes and methods.

classes and objects

You can see the hierarchy easier with the code collapsed and simplified like this:

namespace Adventure
{
    class Game {}
    class Item {}
    class Program { [...] }
}

There are a couple of ways to create new classes. One way is to include them in the same code file we've been working with. Another is to create a new file for each class.

When you start creating larger projects you will probably prefer adding a new class as a separate file. For some new programmers, however, keeping all the code in a single file is easier to understand.

We'll add our code to the existing file for now.

Add the two new classes ("Game" and "Item") to your project.

    class Game {}
    class Item {}

The class definition starts with the keyword "class" and then an identifier. Following the identifier is a code block (a set of curly braces). Statements will be added inside the code block soon.

The order of the classes doesn't matter, but be sure that they are properly opened and closed, and that they are nested inside the Adventure namespace, not each other.

Curly Braces {} and Coding Styles

Coding Styles

There are different styles in which people program. For example, the coding convention for many Java programmers is to have the open brace appear at the end of the same line as the declaration statement like this:

static void Main() {
	Console.WriteLine("Hello World!");
	Console.ReadLine();
}

Visual Studio formats the opening brace on the next line.

static void Main() 
{
	Console.WriteLine("Hello World!");
	Console.ReadLine();
}

The location of the braces makes no difference to the compiler as long as elements are properly nested. It is just a styling convention that is a matter of preference. If you are working with a team or for a company they may request you follow a specific style.

Here is another style alternative:

static void Main() {Console.WriteLine("Hello World!");Console.ReadLine();}

The compiler knows that the curly braces signify the beginning and end of the code block. Inside the code block, the statements are terminated with semicolons. The compiler will not be confused if you don't use the enter key when writing out your statements in this case because the punctuators clearly delineate the code elements, and the elements are properly nested.

You've created two new classes!

Comments

Comments are notes within your code that are ignored by the compiler. They are useful for many reasons, including outlining your thought process, or for notes on what you'd like to add.

Comment Examples

You can start a single line comment with two slashes like this:

//single line comment

A multi-line comment is started with a slash and an asterisk, then closed with an asterisk and a slash, like this:

/* 
multiple line comment
*/

Add Comments

Add comments to indicate you are the author, and the date the application was created. Also include a credit to programmingisfun.com (the code is licensed CC BY).

More about CC BY

The code in this C# Adventure Game series is licensed under a Creative Commons Attribution 4.0 International License.

Which means long as you credit:

  • Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made.

You can:

  • Share — copy and redistribute the material in any medium or format
  • Adapt — remix, transform, and build upon the material for any purpose, even commercially

Example Code

Your code should look something like this:

/*
 * [Your Title]
 * by Your Name, Date
 *  
 * This work is a derivative of 
 * "C# Adventure Game" by http://programmingisfun.com, used under CC BY.
 * https://creativecommons.org/licenses/by/4.0/
 */
using System;

namespace Adventure
{
    class Game
    {
    }
    class Item
    {
    }
    class Program
    {
        static void Main()
        {
            string CharacterName = "John Doe";

            Console.WriteLine("Game Title");
            Console.WriteLine("Welcome to ...");
            Console.WriteLine("What would you like your character's name to be?");
            CharacterName = Console.ReadLine();

            Console.WriteLine("Great! Your character is now named " + CharacterName);
            Console.ReadKey();
        }
    }
}

Press play (F5) to compile and run your application to make sure there are no errors.

In the next section we'll begin moving statements out of our Main() function, and into our new classes.

Quick Quiz

Objects are instances of a .

Correct
Incorrect

A name that a programmer creates for something in their application (like a variable or a method) is called what?

Correct
Incorrect

Which of the following are valid comments in C#? (Select all that are correct)

Correct
Incorrect

To Do: Practice

Practice what you've learned. Make another version of your Madlib, and learn how to add a title to the console window's title bar.

Assignments

Code Files

If you have errors, or just want to check how your code compares in terms of progress, the code examples for this chapter are linked below.

Next Step

In the next section we'll discuss more about methods and expand our code!