C# Classes And Objects

C# Classes And Objects

In this tutorial we’ll talk about classes and objects in the C# Programming Language. What is the point of Classes, and what are they used for? In object-oriented programming, classes were created in an attempt to give programmers the ability to model or approximate the real world in software. There are those that advocate the OOP style, and those that are against it. We will not vouch for one style of programming vs another in this tutorial, but rather examine how to create classes in C# to program in an object-oriented style.

Several Class Files Working Together

In the C# introduction we just completed we only worked on one file, Program.cs. As we start to work with classes and objects in C#, the code powering the application will get split up into multiple files. We’re going to create a little application that tracks a collection of stock prices, and them outputs some calculations about those prices.

We can get started by creating a new project in Visual Studio. I’ll select File->New->Project and then chose a Visual C# Console Application and provide a name of Stocks.
new visual studio console app

Visual Studio now creates a new project for us and creates a namespace of Stocks and the first class which is Program. This class contains the entry point for the application which is the Main method.

Adding A Stock Portfolio

We can add a new class which can be used in the Main method of the program, but where and how do we create a new class? By convention, many C# programmers will create a new file for each class that will be used. You could put all the classes you leverage in one file, but that is not a best practice. To add a new class to our project, we can right-click on the project name, then choose Add, then choose Class.
add class to visual studio project

In the new class dialog, we give the file name of StockPortfolio.cs and then click on add.
name new class file in visual studio

This creates a new file with the same name as the class and scaffolds out the following boilerplate code for us.

The class definition makes use of the class keyword followed by the name of the class. Any code between these curly braces now belongs to this class. StockPortfolio is a member of the Stocks namespace.

Two Categories Of Class Members

Typically there are two kinds of members in a class. The first are for holding data, or state. These are your properties or variables in the class. The state for the StockPortfolio class are the prices entered for a stock.

We also need members of a class that can handle the behavior or action takers. These methods can do work for us. Methods that can interact with a StockPortfolio and do things like add a stock price or compute statistics about the stock prices. The class name is usually a noun, and methods that do work for the class are verbs.

We can start by adding a method that allows us to add a stock price into the StockPortfolio. We’ll call it AddStock(). Any code that goes between the associated curly braces will be executed when this method is invoked. It accepts a parameter of type float, which is named a stock.

Now we need a way to store that state. For this we can use a C# List which refers to a strongly typed list that can be accessed by index. A List makes available methods to search, sort, and manipulate the contained data.

This gives us two classes in the project so far, Program and StockPortfolio. Each of these class has their own file to live in with a .cs extension.

Creating New Objects With Our Class

Now that we have created a class that can do something, we can create a new object to actually put that code to use. In the Main method of the Program.cs file, we can now “new up” and object of type StockPortfolio and store it in a variable. Then, that variable can reference the method we created which is AddStock. So below, we create a new object, then add 6 different stock prices to the object.

Our program doesn’t do a whole lot so far but if we build the solution, set a break point, and then start debugging – we can see that the class is working. It has added the 6 stock prices into the object and the debugger shows us as much.
Visual Studio Start Debugging Example

C# Constructors

What is a constructor and what is it used for? In C# we can use the new keyword to create an object from a class. This is also known as instantiating a class and will trigger a special method known as the constructor which helps to build the object. All classes have a default constructor that exists implicitly in C#.

You might want to create your own constructor to override the default however. This would come in handy for having more control over the initialization of an object. With this approach, you can initialize fields and data for the object and set default values. Defining your own constructor in C# is similar to creating a method. You can use the public keyword and then the name of the class followed by parentheses.

Let’s add a custom constructor to our StockPortfolio class now. In it, we can initialize the stocks variable. Note that the name of the method is the same as the class, StockPortfolio. This is how we know it is a constructor. We don’t need to use a special keyword like __construct in PHP.

Classes and Variables in C#

In C# there are classes and there are variables, but what is the difference between the two? You may have heard before that a class is like a blueprint. You can then use that blueprint to create instances of objects. By using the new keyword in combination with our class name, we can instantiate an object of that type in memory. Our StockPortfolio class can hold a list of stock prices.

An interesting aspect of C#, is that a developer can use a class to define the type of a variable. This is because C# is strongly typed, or in other words, every variable is required to have a type. We saw this above when we wrote the code of:

The portfolio variable in this case is of type StockPortfolio. When a class is used to type a variable, it is so that the developer knows what can be done with an object. In our case, we’ll be able to store stock prices and so some simple calculations on them.

Reference Types In C#

A Class is a reference type in C#. If a piece of data is a reference type, it stores a reference to the data but not the data itself. Reference types are allocated on the heap. When you assign a reference type variable to a different variable, you are passing by value believe it or not. You pass a copy of the reference to the second variable.

C# Access Modifiers

Access modifiers provide for encapsulation and data hiding in object-oriented programming. The three most common access modifiers are public, private, and protected. There are also internal, protected internal, and private protected, but those are not used as often.

  • public can be accessed by any other code in the same class or another class that references it.
  • private only accessible by code in the same class.
  • protected can only be accessed by code in the same class, or in a derived class.

In our class we have a public constructor, a public AddStock() method, and a private stocks property.
C# access modifiers

Static Members In C#

When working with classes, we almost always need to create an instance of the class before we can do any work. In other words, you need to use the new keyword to call a constructor and create an object of that class. What if I told you there was a way to do some work without ever having to initialize an object? Well, there is one such way. It is by use of a static member.

A static method or property in a class is something you can access in code without the need to create an instance of the class first. For example, consider when you make use of the Console.WriteLine() method in C#. You didn’t need to create a new object by using the new keyword first in order to use that method. Why? Because WriteLine() is a static method!

console writeline static method

The method signature for Writeline can be seen here.

Adding A New Class

The highlighted line below would allow us to compute some statistics about the stock prices we have added to the program. It would be nice to be able to look at all the prices and automatically calculate things like the average stock price, the highest stock price, and the lowest stock price. So with that new line, we’re going to need some more code and a new class.

First, we’re going to add a new C# class file like so. It will be named StockStatistics.
new c# class file

We can populate that new class with some code. Notice how we set up a constructor function and initialize both the highest stock price and the lowest stock price. In addition, we have three properties we can use to hold the data.

Now we can circle back to the StockPortfolio.cs class file and add a ComputeStatistics() public method which is of type StockStatistics: The code we just created above.

Lastly, let’s go back to the main Program.cs file and revisit the Main() method.

When the program runs, we should see some interesting output about the stock prices we entered into the program. First, we must build the solution like so to create an assembly.
vs studio build solution

We can run the program by choosing the “Start Without Debugging” option.
Visual Studio Start Without Debugging

If you’re following along and everything went right, we see the output from the program based on all the prices we had entered. Excellent!
vs studio console application

C# Classes And Objects Summary

That concludes this tutorial about a number of features regarding classes and objects in the C# language. We saw how to define a class, as well as how to define a constructor in that class. The constructor of a class can be used to set up initial values, or perform some basic tasks right when an object is first created. We use the new keyword in combination with the name of a class to create a new object from that class. There can be more than one instance of any given class. Of course when talking about object oriented programming, we needed to cover just a bit about access modifiers and how they can provide information hiding and encapsulation. These are the public, private, and protected keywords.