Universal Class: Over 500 Online Certificate Courses
 
 
How to Use Methods in C# Programming
 
 

How to Use Methods in C# Programming

Methods are actually functions, but they are a part of classes. Classes are the foundation for object-oriented programming (OOP), and C# is highly based on OOP architecture. This article covers methods, but first we'll take a brief look at classes and how to create a class.

Classes

We'll discuss OOP in the next chapter, but classes are the highest level of OOP architecture. A class contains several methods and properties used to define your programs. A class represents a component in your program. For instance, you could create an accounting program and you need an internal calculator. Since the calculator is a part of your class, you could create a class named "Calculator" and perform addition, subtraction, division and multiplication. In this example, addition, subtraction, division and multiplication would be the methods.

Before you create a method, you should first know how to create a class. Let's take a look at a class template. We'll use the calculator example.

public class Calculator

{

   public Calculator()

   {

   }

   public int Add(int num1, int num2)

   {

 

      return num1 + num2;

   }

}

In the above code, we created a simple class named Calculator with one method. We've used the public modifier, because we want the class to be available to other parts of the program. If we set the class as private, we wouldn't be able to use it in any other section of the code. We'll cover inheritance and modifiers in the next chapter as well.

The method is the function we created within the class. Notice that this function also has the public modifier, because we want other parts of our code that instantiates this class to use this method. If we set the Add method to private, we could still instantiate the class in other parts of our code, but the private modifier would hide it from being used.

The final part of the class is the function you see that's given the same name as the class. This is the constructor. You need the constructor to instantiate the class, which we'll show you how to do.

Before we move on to methods, the last basic part of OOP and C# that you'll need to know is class instantiation. We've covered variables and data types in previous chapters, and class instantiation is similar. Class instantiation creates a class instance and assigns it to a variable. The following code shows you how to instantiate the Calculator class.

Calculator calc = new Calculator();

This code instantiates the Calculator class and assigns the instance to the calc variable. The constructor we defined doesn't take any parameters, so we don't need to pass anything to the class when we instantiate the reference. With the calc variable defined, we can use the class methods and properties. Unless the class is set with the static modifier, you always need to instantiate it to use its methods.

What are Methods?

Methods are the actions within classes. Classes represent a component, and methods are a part of these classes. They perform actions such as adding two values, sending information, or retrieving data from a database. Methods are often referred to as the "verbs" and class properties are called "nouns." Just like language, class verbs always perform an action and that's why methods should always perform some kind of action in your program.

When you work in OOP development, functions are referred to as member methods or just "methods." It's an important distinction especially if you decide to work in the field. Methods are always a part of a class, and they can be inherited or blocked from inheritance using modifiers. Functions can't be modified or hidden, and they are available to any part of the code as long as it's included in the page.

Your classes don't always need methods. You can create a class with no methods. These classes are usually a part of a C# data model that just represents a list of properties.

Creating a Method

With the class created, you can now create a method. We created the Add method with our Calculator class, so let's take a detailed look at it.

public class Calculator

{

   public Calculator()

   {

   }

   public int Add(int num1, int num2)

   {

     

      return num1 + num2;

   }

}

We copied the class Calculator from the previous section and left it as-is. We still have the Add method that takes two parameters. You'll notice that a method looks similar to a function. The method has a return type, which is the int data type in this example. It has a name, and then any parameters are in the following parenthesis. These two variable parameters are then used to return the sum of two numbers contained in num1 and num2.

We mentioned that the public modifier allows any other parts of your code to use the method. You can make your methods public or private. If the modifier is public, you can instantiate your class and then use the method with your variable. If you set it as private, you can still instantiate the class but you aren't able to use the function. Choosing the right modifier can make a difference when protecting certain code from being altered. For the most part, your methods will be public.

You can have several methods in your classes. Each member method can have its own parameters and modifiers. Let's add two more methods to our Calculator class.

public class Calculator

{

   public Calculator()

   {

   }

   public int Add(int num1, int num2)

   {

      return num1 + num2;

   }

   public int Multiply(int num1, int num2)

   {

     

      return num1 * num2;

   }

   public int Subtract(int num1, int num2)

   {

 

      return num1 - num2;

   }

}

We added two methods named Multiply and Subtract. They have the same modifiers and use the same variable names. A variable created within a class is only available to the class itself. This means that you can use the same variable names for each method. The variable is destroyed when the method is finished executing. This is called variable scope.

Classes can have global variables. These variables are member variables, and they usually have the m_ prefix. The m_ prefix isn't a requirement, but it standard with coding standards to identify member variables using the m_ prefix. Let's take a look at the same class with a member variable added.

public class Calculator

{

   private int m_result = 0;

   public Calculator()

   {

   }

   public int Add(int num1, int num2)

Interested in learning more? Why not take an online class in C# Programming?

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public int Multiply(int num1, int num2)

   {

      return num1 * num2;

   }

   public int Subtract(int num1, int num2)

   {

      return num1 - num2;

   }

}

In the above code, we added a member variable and used it within our Add method. We also gave this member variable the private modifier. When you create member variables, you usually set them to private. They can then be called and manipulated only within your class. It greatly reduces the chance for bugs in your code. Notice also that we used the m_ prefix to indicate throughout the code that the variable is a member.

The Add method uses the member variable and assigns the sum of num1 and num2 to it. We can access the variable because member variables are global. Global variables can be accessed and assigned variables from anywhere in the class. They are restricted to the class unless you create the variable with the public modifier, which again isn't standard.

All three of our methods have two parameters. In C#, you can set a default value for each parameter. Variables with default values must be at the end of the parameter list. Let's take a look at some sample code.

public class Calculator

{

   private int m_result = 0;

   public Calculator()

   {

   }

   public int Add(int num1, int num2 = 0)

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public int Multiply(int num1, int num2)

   {

      return num1 * num2;

   }

   public int Subtract(int num1, int num2)

   {

      return num1 - num2;

   }

}

We added a default value to the num2 variable. If we used this class and passed only one value to the Add method, the first variable num1 contains the value passed and the second variable num2 contains the value of 0.

Let's take a look at the code to instantiate the Calculator class and use these methods.

Calculator calc = new Calculator();

int result = 0;

result = calc.Add(1, 2);

Notice that we first instantiated the class and assigned the instance to a variable. We then create a variable for the calculation. The Add method returns an integer value, so we must define an integer variable to obtain the results from the calculation.

The third line of code is where we call the Calculator class member method. When you call a method, you use the class variable and then type a dot. When you type the dot, Visual Studio uses a program called Intellisense. Intellisense shows you a popup of all available member variables and methods. It's a helpful tool that helps you find the appropriate method or variable that you need to use. When you have dozens of methods in one class, this tool makes it easier to find the right method instead of digging into the class code.

We pass two values to the Add method. Remember that we have a default value for the second parameter, so we can also send only one value and the method won't give you an error. If we attempt to send only one value to the other methods, the compiler would give you an error and you won't be able to compile your code.

Since the Add method returns a value, we must assign the results to a variable. The variable data type must match the data type returned by the method. In this example, we create an integer variable named result and assign the Add result to it. If we printed this value, we'd see that the result variable now contains the value of 3.

Overloading Methods

We have a method that adds two numbers, but what if we wanted to add three numbers? We wouldn't be able to use the method. We could make another method with the same name, but the other option is overloading. Overloading a method means you make a function with the same name but use different parameters. Even though the method has the same name, the compiler sees it as a different method since parameters are not the same.

Let's take a look at some sample code.

public class Calculator

{

   private int m_result = 0;

 

   public Calculator()

   {

   }

   public int Add(int num1, int num2 = 0)

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public int Add(int num1, int num2, int num3)

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public int Multiply(int num1, int num2)

   {

      return num1 * num2;

   }

   public int Subtract(int num1, int num2)

   {

      return num1 - num2;

   }

}

We created a second Add method. This Add method takes three parameters and won't cause a compiler error even though it has the same name as the previous method. We don't assign a default value to this method, because we always want to require 3 parameters passed to differentiate it from the first Add method.

You can overload any method dozens of times provided each new method has different parameters. You can also overload your methods by using a different return data type. Let's see an example of an overloaded method with a new data type.

public class Calculator

{

   private int m_result = 0;

   public Calculator()

   {

   }

   public int Add(int num1, int num2 = 0)

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public int Add(int num1, int num2, int num3)

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public float Add(float num1, float num2 = 0)

   {

      m_result = num1 + num2;

      return num1 + num2;

   }

   public int Multiply(int num1, int num2)

   {

      return num1 * num2;

   }

   public int Subtract(int num1, int num2)

   {

      return num1 - num2;

   }

}

Notice that we added a third Add method. This method has the same number of parameters but a different return data type and parameter data types. These two factors distinguish the method from the others, so it's a valid overload. We can still use the same variable names throughout the overloaded methods because the scope never changes.

Let's take a look at how you call an overloaded method.

Calculator calc = new Calculator();

int result = 0;

float result2 = 0;

result = calc.Add(1, 2);

result2 = calc.Add(1.1, 2.2);

Since we call the Add method that returns a float value, we need to create a float variable to contain the result. Notice that we call the two overloaded methods in the same way. Since the first method call adds integers and the second method call adds floats, the compiler can match the appropriate method with the right call.

Recursion
 
With static methods, you can perform a function called recursion. Recursion occurs when the method keeps the previous call's values and then calls itself again. Let's take a look at a recursive method.

public class Calculator

{

   private int m_result = 0;

   public Calculator()

   {

   }

   static int Recursive(int num1)

   {

      if (num1 >= 10)

      {

          return num1;

      }

      return Recursive(num1);

   }

}

Notice that the return statement calls the Recursive method again. When you call recursive methods continually, you need a condition to stop the loop or you can crash your program in the same way you can create an infinite loop.

In this example, the Recursive method executes until the num1 variable reaches the value of 10. Once the condition is reached, the method is no longer called.


Recursive methods are useful when you need to iterate through a list of values. For instance, you use recursion when you iterate through folders on a hard drive. You need to keep the parent folder and then obtain an aggregate list of subfolders. When subfolders have subfolders, you then iterate through them. This activity requires recursion.

 

Most of your classes will contain methods as you code your application. Remember that C# is based on OOP, so you need classes and methods to perform actions in your program. These methods work with member variables to create efficient code that can be reusable throughout your entire program portfolio.

 
 
Popular Courses
 
Learn More! Take an Online Course...