CSCI 1301

Methods

1. Learning Objectives

  • What are methods
  • What are parameters
  • What is a return type and
    • How to write methods that return information
    • How to write methods that do not return information
  • How to perform method calls

2. What are Methods

In object-oriented programming, methods describe the behavior or actions that an object can perform or undergo. Within a class definition we define different methods that can occur to an object instantiated from that class. Then, during runtime, we can call these methods to perform these actions. We can say "we will make a method call" and the selected action will occur. Much like with properties, we choose what methods to define based on what we want to represent in the program.

Visual Example

Recall the cookie example. This time we have added methods.

methods

  • The class now has two methods: Eat and Bake
  • These methods define what we can do with a cookie
  • Method does not execute automatically first you must instantiate an object then call the method to perform the selected action
  • Notice that you perform these actions on the actual objects; not the class.

You already know many methods

You may not have realized it yet but you have already used many different methods throughout this semester. Main is a special method that gets called when program launches. Here are some other methods you should recognize:

Console.Write("Some string");

Write method displays information on the screen

random.Next();

Next method chooses a random integer value

Console.ReadLine();

ReadLine method returns input from a user

" some string ".Trim();

Trim method removes whitespace from a string

You can identify methods from the parentheses that follow them. In fact, the getters and setters we wrote earlier are also methods - they are methods with special purpose of accessing and modifying property values in object-oriented programs.

3. Exercise: Identify Methods

Let's practice identifying methods. Assume you want to model the following entities in your program. What methods would you choose? Write down your answers on a piece of paper or in text editor before you continue. As before, there are no absolute correct answers, but some answers are more practical than others.

A) Car

car

B) Sandwich

sandwich

C) Book

book

After you are done you can compare your answers to this solution.


4. Methods in C#

Methods are defined inside a class. We will start with a new class MyClassWithMethods. It has has some simple methods to give you an preview of the syntax:

MyClassWithMethods.cs
1public class MyClassWithMethods{
2
3 // METHOD SYNTAX
4 // 1. access modifier
5 // 2. return type
6 // 3. identifier
7 // 4. parameters
8
9 public void GreetUser(){ // method signature
10 Console.WriteLine("Hello User!"); // method body
11 }
12
13 public void SayBye(){
14 Console.WriteLine("Bye User!");
15 }
16}

Method Syntax in C#

  • start with access modifier (public or private)
    • Recall private indicates the method cannot be called from outside the class
  • return type
    • the example above uses void to indicate method will not return anything
    • when using other return types such as string or int, you must ensure the method actually returns a value, meaning the implementation must match the specified return type
  • method name i.e. identifier
    • use PascalCase (capitalize each word).
    • Choose method names that refer to the action they perform
  • parentheses containing a list of parameters
    • Method can have zero or more parameters
    • the methods in the above example have 0 parameters; therefore they have empty parentheses ()
    • this is not always the case more about parameters next!

The combination of method name and its parameters is called method signature. In the example above lines 9 and 13 are method signatures.

A method should perform a single action. If your method has many lines of code ( > 25 is a good rule of thumb) you might want to consider breaking it down into smaller methods.

5. Parameters

When you define methods you must also define its parameters. Parameters represent the data that is required by a method to perform its job. The method caller will provide this information to the method at the time of making a method call.

A method may require:

  • 0 parameters
  • 1 parameter
  • 2 or more parameters

For the purposes of this course, when we work with parameters we assume those parameters are always required. However, be aware that it is possible to write methods where some parameters are optional, and it is quite common in practice.

Consider this class we saw earlier and observe the changes:

MyClassWithMethods.cs
1public class MyClassWithMethods{
2
3 // this method does not have any parameters
4 public void GreetUser(){
5 Console.WriteLine("Hello User!");
6 }
7
8 // this method has 1 parameter
9 // caller MUST provide an integer when calling this method
10 public void MultiplyByTwo(int number){
11 Console.WriteLine($"{number} * 2 is {number * 2}!");
12 }
13
14 // this method has 2 parameters
15 // caller MUST provide two integers when calling this method
16 public void AddNumbers(int a, int b){
17 Console.WriteLine($"Adding {a} + {b} = {a + b}!");
18 }
19}
  • GreetUser method takes no parameters. You can recognize this from looking at the method sinature, because the parentheses following the method name are empty.
  • MultiplyByTwo method requires exactly 1 integer type parameter.
  • AddNumbers method requires 2 parameters, both must be integer type.

Specify a comma-separated list when a method requires more than 1 parameter. You can have as many parameters as you need. For example, to modify AddNumbers to require 3 parameters, we would change the method definition to say:

public void AddNumbers(int a, int b, int c) {
// do something with a, b, and c
}

Once you have specified parameters for a method, you can refer to those parameters inside the method body and perform different actions with them. The scope of parameters is defined by the method body - that is, you can refer to these parameters inside the method body, but not in the rest of the class. For example, a is defined inside AddNumbers method, but referring to a inside GreetUser method would cause an error.

The choice of how many parameters you need depends what the method does. You will learn to identify what parameters you need over time as you practice implementing your own methods.

6. Returning Values from Methods

All methods we have looked at so far have had return type void. This is not always the case. It is very common to write methods that return a value to the caller.

For example, if you call ReadLine() method, it returns a string value that represents user input. If you call Next() method from Random class, it returns you a random integer value. If you call TryParse, you will get a return value that indicates if the parse operation was successful or not.

A method can return 0 or 1 piece of data and you indicate the expected behavior by specifying a return type in the method declaration.

Specifying Return Types

Observe the method declarations below. Return type is the second keyword, following the access modifier. Notice that all of these methods have different return types.

MyClassWithMethods.cs
1public class MyClassWithMethods{
2
3 // return type is void
4 // method does not return anything
5 public void GreetUser(){
6 Console.WriteLine("Hello User!");
7 }
8
9 // return type is string
10 // expect to get a string when calling this method
11 public string Message(){
12 return "Hello World!";
13 }
14
15 // Call this method with a integer
16 // and it will return that integer times 2!
17 public int MultiplyMe(int number){
18 return number * 2;
19 }
20}

Method implementation must match the indicated return type. That is,

  • If you specify return type void, you CANNOT return anything
  • If you specify return type string, you MUST ALWAYS return a string
  • If you specify return type int, you MUST ALWAYS return an int (etc.)

Failure to do so will cause a syntax error.

Notes on return Keyword Behavior

return keyword is used to send information from a method back to its caller.

Often you will see return at the last line of a method. However, if return is encountered earlier, the execution of that method ends immediately at the line that contains return. This is similar to the behavior of break statement inside a loop.

If you place a switch statement in a method, instead of breaking you can also use return. Here is an example of that behavior:

MyClassWithMethods.cs
1public class MyClassWithMethods{
2
3 // using return keyword in a switch statement
4 // with multiple returns in one method
5 public string SwitchExample(int number){
6 switch(number){
7 case 1:
8 return "Hello 1";
9 case 2:
10 return "That is number 2!";
11 default:
12 return "Some other number";
13 }
14 }
15}

7. Performing Method Calls

So far we have defined methods, but these methods do not execute until we perform a method call.

Observe the example below that demonstrates an implementation of a class with three different methods, each with a different numbers of parameters and different return types (see MyClassWithMethods.cs, use the file icon to toggle between views). Then, in the Main.cs within Main method, you can observe how these methods are being called.

Recall when defining a method, we also define its parameters. When performing a method call, we pass in arguments that match those parameters specified in the method declaration.

There is a small semantic difference between parameters and arguments. People generally understand what you mean if you mix these two terms. The difference is this: parameters are part of the method definition. Arguments are pieces of data the concrete values of matching data type(s), provided to the method during a method call.

VERY IMPORTANT! The order and data type of arguments in a method call must match the method definition.

For example if a method is defined as

1public void MyMethod(int a, string x) {
2 // ...
3}

it must be called it with arguments of matching data type in the same order:

1// method call example:
2MyMethod(5, "someStringValue"); // must be int, string

In this example the first argument must be an int value, and the second argument must be a string value. You will get a syntax error if data types do not match, they are in wrong order, or if you try to pass too many or too few arguments.

8. Method Calls Within Same Class

The previous example demonstrated how to call methods defined in one class from another class. But sometimes we might want to create private methods to control who is allowed to execute the method and when the method is allowed to execute. Remember private methods are not accessible from outside a class. Therefore to call private methods, the method call must be performed within the same class.

The example below demonstrates how to make a method call within the same class (line 9). Notice when calling a method within the same class, you do not need an object reference; call the method by its identifier.

Accessing private properties

Recall that private class fields cannot be accessed from outside a class. However, they can be used by methods within the same class. The private access modifier controls what information is accessible to outsiders of the class. Access modifiers have no impact between members of the same class. See the example below that demonstrates this behavior.


9. Summary

What are methods?

Methods describe the behavior (or actions) and object can perform or undergo. Methods are defined in a class. A method call is required to execute a method.

What are parameters?

As part od a method declaration we specify the information that is required by the method to perform its job. This information is called parameters. Method may require zero of more parameters.

What is a return type?

Method return type indicates if a method will return information to a caller. Method can return 1 piece of information, or return nothing (return type void). We can see what the expected behavior is by observing the return type on the method definition.

How to write a method that returns information

in the method definition, specify a return type:

1// specify return type
2public string WillReturnString(){
3 // must return something inside method body
4 return "some string";
5}

How to write a method that does not return information

1// specify void as return type
2public void NoReturnHere(){
3
4 // this method cannot return anything!
5 // no return keyword inside this method body
6}

How to call class methods

To call a method, we need to know the name of the method and what the required parameters are. If a method has been defined in a separate class, we need to first instantiate an object, then refer to the object to call the method. Assume we have following class definition:

SomeClass.cs
1public class SomeClass{
2
3 public void SomeMethod(int numParam){
4 // method implementation
5 }
6}

To call this method we need to

  1. instantiate an object
  2. perform a method call
Main.cs
1// Step 1. object instantiation
2SomeClass myObj = new SomeClass();
3
4// Step 2. method call
5myObj.SomeMethod(10);

When calling a method within the same class, object reference is not needed.

AnotherClass.cs
1public class AnotherClass{
2
3 public void DoActionA(){
4 // I will do something
5 }
6
7 public void DoActionB(){
8
9 // calling this method
10 // calls another method
11 // in the same class
12 DoActionA();
13 }
14}