Tag Archives: methods

Methods in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Method names should follow a consistent naming convention throughout your code eg. using camel case or mixed case. Examples of suitable method names include CalculateScore, AddNumbers, MultiplyNumbers, GetUserDetails, etc.

Watch the video below and then scroll down for examples and sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is an access modifier?

Access modifiers include public and private (or just left empty). Public means other parts of the program can see and use this method. If we don’t want that we use private instead or no access modifier (leave it out).

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that many functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a calculator that is used to add two numbers together. There are two parameters in this method (separated by commas). The parameters in this method are num1 and num2. These are the two numbers that will be added together (they are of the float data type). Notice that the return type is also float meaning that the result of this method (the sum of num1 and num2) will be returned as a float value.

public static float AddNumbers(float num1, float num2)
 {
   float total = num1 + num2;
   return total;
 }

The method above will add two numbers together (the two parameters num1 and num2) and then return the answer as a float back to the part of the program that called the method.

The word static means that this particular method is associated with the class, not a specific instance (object) of that class. What this means is that you are able to call a static method without actually creating an object of the class.

Many methods have the word void in their declaration. The word void basically means that the method will not return any value to the part of the program that called it.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named AddNumbers, you would write:

AddNumbers();

If the method contained a parameter or multiple parameters (eg. the values 5 and 10), then they would be included inside the brackets like this:

AddNumbers(5,10);

The below example shows how to call a method and pass variables into the method. You do not need to write int inside the brackets where the function is called.

int number1 = 10;
int number2 = 30
AddNumbers(number1,number2);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method AddNumbers() in the example code above returns a value, then it should be stored in a variable or used in a statement, for example:

int result = AddNumbers(5,10);

Sample code

Here is an example using parameters and a return type of void. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      AddNumbers(5, 10);
    }
    public static void AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      Console.WriteLine("The sum of the two numbers is " + total);
    }
  }
}

Here is an example using parameters and a return type of int. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers(5, 10);
      Console.WriteLine(answer);
    }
    public static int AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      return total;
    }
  }
}

Here is an example using no parameters. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers();
      Console.WriteLine(answer);
    }
    public static int AddNumbers()
    {
      int total = 5 + 10;
      return total;
    }
  }
}

Methods in C#

In C#, methods are like functions. Methods can be created to store a list of instructions that can then be called on later on in the program. Methods can be used more than once so if there are instructions you need to use constantly throughout a program, then it makes sense to write them only once and call on them when needed rather than writing the instructions multiple times.

Methods also allow you to break up different tasks in your program an make them easily identifiable, rather than having a heap of different tasks in one big block of code (or spaghetti code).

The code below shows how to make a command-line calculator that breaks up each function of the calculator (adding, subtracting, multiplying and dividing numbers and checking which calculation option the user chose). The methods are declared and then called on in the program.

Sample C# code

using System; // tells this file we will be using the System namespace

namespace MyCSharpApp // new namespace called MyCSharpApp which will contain classes
{
  class MainClass // new class called MainClass
  {
    public static void Main (string[] args) //new method called Main (executes as soon as the app runs)
    // which has to be a public static void and will receive an array of strings
    {
      Console.WriteLine ("Hello World!");
      Console.WriteLine ("What is your name?");
      // WriteLine method is used to write a string to the console
      string name = Console.ReadLine();
      // we can add this method so the program will wait until the user
      // types something in or presses a key to continue
      // By creating a variable called name, now the ReadLine input is stored in a variable
      Console.WriteLine("Hi there, " + name);
      calculator ();
    }

    public static void calculator()
    {
      Console.WriteLine("Enter two numbers...");
      Console.WriteLine ("Enter the first number:");
      float num1 = float.Parse (Console.ReadLine ());
      // float.Parse() is used to convert string to float
      Console.WriteLine ("Enter the second number");
      float num2 = float.Parse (Console.ReadLine ());
      // could write Console.WriteLine(num1+num2);
      // or could use a method instead...
      Console.WriteLine ("Select an option\n1 - Add\n2 - Subtract\n3 - Multiply");
      int option = int.Parse(Console.ReadLine());
      checkOption (option, num1, num2);
    }

    // this creates a new method called addNums which takes two float arguments
    public static float addNums(float n1, float n2)
    {
      float answer = n1 + n2;
      return answer;
    }

    // this creates a new method called subtractNums which takes two float arguments
    public static float subtractNums(float n1, float n2)
    {
      float answer = n1 - n2;
      return answer;
    }

    // this creates a new method called multiplyNums which takes two float arguments
    public static float multiplyNums(float n1, float n2)
    {
      float answer = n1 * n2;
      return answer;
    }

    public static void checkOption(int option, float n1, float n2){
      if (option == 1) {
        Console.WriteLine ("The answer is: " + addNums (n1, n2));
      }

      else if (option == 2) {
        Console.WriteLine ("The answer is: " + subtractNums (n1, n2));
      }

      else if (option == 3) {
        Console.WriteLine ("The answer is: " + multiplyNums (n1, n2));
      }

      else {
        Console.WriteLine ("Option not recognised.");
      }
    }

  }
}

Creating and using methods (functions) in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

In Unity, the Start method contains all of the code that will run for an object when a scene begins. The Update method contains all of the code that runs every single frame of the scene.

This is the basic syntax of a method:

<return type> <name>(<parameters>)
{
// code that runs inside the method goes here
}

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Watch the video below to learn how to create and use methods in C# and then scroll down to see the sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that the Start and Update functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a game in Unity that is used to apply damage to a player’s health. There are two parameters in this method (separated by commas). The parameters in this method are damageAmount and health. Notice that the return type is int.

int applyDamage(int damageAmount, int health)
{
 return health - damageAmount;
}

The above method is a simple example. In an actual game, the player’s health could instead be stored in a variable inside a script so it wouldn’t need to be read into a method. However, the example above shows the structure of methods.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named myMethod, you would write:

myMethod();

If the method contained a parameter (eg. the value 10), it would be called like this:

myMethod(10);

The below example shows how to call a method and pass a variable into the method. You do not need to write int inside the brackets where the function is called.

int x = 10;
myMethod(x);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method myMethod() in the example code above returns a value, then it should be stored in a variable, for example:

int result = myMethod(x);

Here is another example of the applyDamage() method:

using UnityEngine;
using System.Collections;
 
public class hitFromLaserScript: MonoBehaviour {
 
 void Start()
 {
 int x = applyDamage(5, 100);
 print ("Player health: " + x);
 
 }
 
 int applyDamage(int damageAmount, int health)
 {
 return health - damageAmount;
 }
 
}

Objects, properties and methods in JavaScript

Object-oriented programming is a type of programming where programmers can define not just the data type of a data structure,  but also the different types of operations (or functions) that can be applied to a data structure. Under this model, a data structure is an object which consists of both data and functions. Programmers can create relationships between different objects. For example, objects can be given characteristics that belong to another object.

Programming languages which support object-oriented programming include Java, C++, Python, Visual Basic .Net, Ruby, and of course JavaScript.

In Javascript, an object is something that can have properties and a method is an action that you can perform on an object. A property is something about an object (eg. the length of a string).

Watch the video below first, and then scroll down to view the sample code.

In the example below,  the sentence is the object, the length is the property of the object, and the method is the action used to convert the string to uppercase letters. Look at the sample code below to see how properties and methods are used on objects.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Objects, properties and methods</title>
 <script type="text/javascript">
 
 /* Remember that JS is an object-oriented language. 
 An object is something that has properties in JS.
 A method is an action you can perform with an object.
 A property is something about an object (eg. the length of a string).
 
 In the example below, sentence is the object, length is the property of the object and method is the
 action used to convert the string to uppercase letters.
 To work with properties, we use the syntax objectname.propertyname 
 A method will always be followed by brackets eg. objectname.methodname()
 A method will sometimes require parameters.
 */
 
 var sentence = "Hello world";
 // This is an example of using a property
 document.write(sentence.length,"<br/>"); // the <br/> tag is simply used to make a new line here
 // This is an example of using a method.
 document.write(sentence.toUpperCase());
 
 //With document.write , document is the object and write is the method.
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Using the getElementById() method