Tutorial: Classes and Methods in C#

Now that we have a basic understanding of inputting, outputting, and storing compile-time variables, let’s move on to one of the most important parts of C# and object oriented programmingclasses.

Classes work just like their name imply; Each class has a specific set of parts: Private/public data (variables to set up the class and for use within it), constructor methods (which set up our private data for the methods to use), functional methods (like calculators), and return methods (the methods that send back our private data). Classes make up every part of our program which is what makes them extremely important to understand, and allow us to create easy to reference code, and also compile it into a .dll file for implementation in other programs should you desire to do so. We’ll get into DLLs next time.

Now for constructors. You should always have at least two:

  • A default constructor. Having a default constructor allows the compile to ensure that the class will be properly constructed even without input. They’re also important for extending classes, which we’ll talk about later on as well. For safe measure, always put it first.
  • An argument constructor. These constructors are set up just like how we’d call our methods, like Console.WriteLine() which took a string to print off. However, since we’re going to be writing the methods, we have to include what type of data it can use. (Ex: WriteLine would be set up like WriteLine(string tbp) where tbp is the variable that we put in to print off.)

Here’s a basic diagram of how to order methods and private data in a class to make them easier to understand:

Class diagram

Child class

To make things easier to understand, let’s lay out a common example, such as a child. To set things up, we need to know what a Child has. For now, let’s say every Child has a first name (a string), a last name (a string), an age (an int), and a favorite letter (a char) because why not?

Now, let’s lay it out.

So now we can currently construct our Child class. To do so, all you have to do is declare it like a new variable, and what you want to input! Make sure that when declaring your class, you use the new keyword, and put in the proper arguments (The variables in parentheses) in order, unless calling the default constructor.

Ex: Child George = new Child(“George”,”Washington”,67,’G’);

(I can’t actually confirm that George Washington’s favorite letter was G, please don’t cite that)

Now we’ve created our first class! But now we have a problem: it can’t do anything. So how do we make our class actually do something? We use something of familiar vocabulary—methods. To access and return our data from the class, we’ll have to write methods for it.

There are a few different types of methods, but there are two main ones we’ll have to understand:

  • Variable methods – These types of method are to return a specific data type based on the method header. (public int sum(int num1,int num2) {} for example would have to return an int or a compile-time error would be thrown.) These take any of of argument/parameters, but will break if they do not return the same type of variable as the header implies.
  • Void methods – A void method is a type of method that can also take in any type of arguments, but are not required to return anything. They are specifically written to either call other methods, such as writing to the console, or calculating and setting/constructing our class’s private data. A return statement is not necessary to be put at the end of a void method.

Another important thing to understand with methods is the keyword static, which goes after the word public/private and before the type declaration. A static method is one that can be called at any time, and does not reference any sort of private data. These types of methods would be used if you wanted to repeat something such as printing off a specific set of numbers to the console without referencing private variables within the class. They’re especially useful when calling a method inside of a static method, but only if you’re going to use specific arguments for it. (Main should start to make more sense now)

Here’s a couple of examples. Let’s say you wanted a method that would return the sum of two doubles, and a void method that would print off the result of adding 5.381087 and 8.126, then rounding it to the second decimal place (We’ll use a preset method in the Math class called Math.Round() which takes a double or a decimal and the place to round it to).

Now if we were to call our printSum() method, it would print out 13.51 to the console. If you want to try out those methods for yourself, feel free to add them above your Main() method in another program, just don’t try and nest them within Main or you’ll get an error message.

So, since we now understand how to write and call methods properly, let’s go back to our Child class. We want to set the myWholeName variable to their first + their last name, and we’ll need a method to return their whole name, their age, and one last method to return their favorite letter.

Let’s write those 4 methods like so:

That’s the whole class! To try it out, copy and paste your new class above your Program class. Then inside Main, declare and construct a new Child variable with whatever name you want, and inside the parentheses be sure to include a first name, last name, age, and favorite letter. In case you forgot, it looks like this:

Ex: Child George = new Child(“George”,”Washington”,67,’G’);

Now we want to calculate his whole name, and then print it off to the console, as well as his age and favorite letter. We want to have something like so:

Name: George Washington

Age: 67

Favorite Letter: G

Using your skills in printing off information and calling methods, you should understand this next part pretty easily by now. First off, we have to calculate his whole name. Do so by simply calling George.setWholeName(); and it will set the variable within the class for us. Then you can just call your return methods within inside of Console.WriteLine()! You can also store the results in new variables and then print them off, but for simplicity, let’s do it all in one line. (Don’t forget to put Console.ReadKey(); at the end!) Here’s the code if you’re having trouble:

Your results should look just as expected! If not, compare your code to mine, then give it another shot. You should get this:


Congratulations on writing your first class! Now try this—go back to your Area and Perimeter program from the last lesson and write a class named Shape which has a ints length and width as private data, add your constructor (no need for a default constructor in this case), then write methods public int calcArea() and public int calcPerimeter() which should return the area and perimeter given the length and width, respectively. Add the Shape class above your Program class again, then in Main, make a new Shape by having the user input the length and width and print off the area and perimeter to the console.

Area and Perimeter 

If you’re having trouble, here’s what your end result should look like:

Before we finish up the lesson however, let’s change up our print statements to be a bit simpler. As you may have noticed, in the example above I stored the result of the area and perimeter inside of a new variable. C# allows us to do something pretty interesting within our Write/WriteLine statements. We can write both variables within one line, as if they were an index, and print them off with so. You can do this by wrapping the index of the variable (the index is what place it is between all the other variables, not including things in quotes) within curly brackets {} and placing them inside of quotes. If I were to write (“Length: {0}”,length), whatever I put in for length would be printed out like “Length: 5” and so on. Inside of quotes, you can also put \n to start a new line without making another WriteLine statement. So now, if you were to get rid of your two WriteLine statements like I have in the example above, you can instead write:

Console.WriteLine(“The area is {0} \nThe perimeter is {1}”,newArea,newPeri);

Here’s a screenshot as well if it makes things easier to comprehend:


It works exactly the same! Make sure not to put a space after the \n though or the next line will start with that space, and it just looks weird. Anyways, now we have a full understanding of classes, methods, and keywords such as new, return, static, and void as well. Keep practicing with those, and next time we’ll get into writing DLL and implementing files and using them in our programs, which should be a bit shorter of a lesson. After that, we’ll start getting into Windows Forms Programs before touching on more advanced things such as subclasses, the super keyword, extending and implementing, interfaces, and abstraction. Stay tuned for more!