IMPORTANT PLEASE READ!
Website development and design blog, tutorials and inspiration

Passing Parameters to Methods and Return Values in C#

How to pass parameters to methods

By , Written on in C#

Passing Parameters to Methods and Return Values in C#

1,090 words, estimated reading time 5 minutes.

In this tutorial, we will look at some more advanced features of methods. We will see how to pass parameters to a method and how to return a value back, and cover more advanced features like variable length parameters, passing by reference and output parameters.
 
C# Programming Series
  1. Introduction to Programming
  2. What is C#?
  3. Your First Console Application in C#
  4. Introducing Methods and the Main() Function in C#
  5. Introducing C# Classes and Structs
  6. C# Data Types, Variables and Casting
  7. C# Program Flow Control and Entry Points
  8. Passing Parameters to Methods and Return Values in C#
  9. C# Access Modifiers and Scope
  10. C# Interfaces and Classes
  11. Using Namespaces in C#
  12. C# Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. C# Constants and Read-Only Variables
  16. Error and Exception Handling in C#
  17. Using Recursion in C#
  18. C# Operator List
  19. Class Inheritance in C#
  20. C# Class and Method Attributes Explained
  21. C# Class Constructors and Destructors
  22. C# Generics Variables
  23. XML Serialization and Deserialization
  24. C# String Formatting Examples

This article relates to an old version of the .Net Framework. While the contents are still relevant, future versions of the framework may change, or improve upon, the contents of this article.

In a previous tutorial we created a Hello World program and we saw the static void Main() method and we created another method the same way using static void myMethod()

What do we do if you want to pass some data to your new function and have it return a value back? How do you capture the result? And how do you pass a parameter? Let's have a look using a simple program to add numbers.

Starting off with a new console project, we are going to create a method called addNumbers which will take two integers as parameters. This is done by defining a variable within the brackets of the method. Parameters are separated by a comma.

  1. static void addNumbers(int x, int y)

This will tell the compiler that the addNumbers will need to have two integers, x and y. This method can only be called with the correct number of parameters, and they must be of the right type.

  1. addNumbers(); // Will not work as there are no parameters
  2. addNumbers(5); // Will not work as the method requires two parameters
  3. addNumbers("1", "2"); // Will not work as these are strings
  4. addNumbers(5, 5); // Will work
  5.  

Full code listing

  1. using System;
  2.  
  3. class AddNumbersProgram
  4. {
  5. static void Main()
  6. {
  7. addNumbers(5, 5);
  8. }
  9.  
  10. static void addNumbers(int x, int y)
  11. {
  12. int z = x + y;
  13. Console.WriteLine("Result of {0} + {1} = {2}", x, y, z);
  14. }
  15. }

When run this program should show

Result of 5 + 5 = 10

Returning a Value

Instead of outputting the calculation to the screen, you may wish to return it back to the calling method (the method where the addNumbers method was called from. In this case Main).

We need to make a few changes to the method. We need to change the word void (which means the method does not return a value) into int (which means the method returns an integer number). The method declaration now becomes:

  1. static int addNumbers(int x, int y)

Now we need to remove the Console.WriteLine line and replace it with:

  1. return z;

Finally, we need to capture the return result within Main.

  1. int result = addNumbers(5, 5);

And that's all we need to do to make our method return a value. We just need to change our calling function to pick up the result.

  1. using System;
  2.  
  3. class AddNumbersProgram
  4. {
  5. static void Main()
  6. {
  7. int result = addNumbers(5, 5);
  8. Console.WriteLine("Result of addNumbers = {0}", result);
  9. }
  10.  
  11. static int addNumbers(int x, int y)
  12. {
  13. int z = x + y;
  14. return z;
  15. }
  16. }

If a method is to perform a calculation, it is far better to have it return the result on its own, rather than including formatting and other information, as the result on its own can be used from any other methods that may need to use the same calculation. By returning the formatted string, you are limiting that method to that particular task.

A Few Notes

The value you use to hold the result of a function must be of the same type as the return type of the method you are calling.

The value you return through return myValue must be of the same type as the methods return type. This is because C# is a type safe language. That means the compiler will make sure that you are not trying to place a string in a variable that is declared as a number.

Other ways of passing data

There are three ways of passing data to and from a method. We have just seen the first way - by value, but there are two other ways.

By Reference

Variables passed in by value are read-only. Within the method, you cannot assign a value to a parameter unless it is passed by reference. When you pass a parameter by reference, you pass the memory location rather than the data. The method can then access and modify the memory location.

You can specify that a parameter should be passed by reference using the ref keyword. Parameters passed in this manner are read/write, you can read the value and also write a new value which can be picked up by the calling method.

  1. static void myMethod(ref int myInt)

To call a method with the ref keyword, you also need to specify ref in the parameter list.

  1. int z = 2;
  2. myMethod(ref z);

Output Parameters

The third way is through the use of output parameters and the out keyword. This allows values to be passed out, but not in, thus it is a write-only parameter.

  1. static bool myMethod(out int myInt)
  2. {
  3. Console.WriteLine(myInt); // Will Error;
  4.  
  5. // Return a value
  6. myInt = 10;
  7. return true;
  8. }

You can see that this method will allow you to return more than one value back to the calling method. You can have as many out parameters as you need.

To call a method without parameters you need to specify out in the parameter list in the same way as you do with reference.

  1. using System;
  2.  
  3. class OutputParameterDemo
  4. {
  5. static void Main()
  6. {
  7. int a;
  8.  
  9. if (myMethod(out a) == true)
  10. {
  11. Console.WriteLine(a);
  12. }
  13. }
  14.  
  15. static bool myMethod(out int myInt)
  16. {
  17. // Set myInt to a value
  18. myInt = 10;
  19.  
  20. // Return success
  21. return true;
  22. }
  23. }
  24.  

Difference between reference and output parameters

One of the main differences between the two is that parameters passed by ref do not have to be assigned to, whereas output parameters must be assigned to before the method exits.

Variable Length Parameters

Sometimes it is required to pass n number of parameters to a method. A good example is a method to calculate the average of a series. You could pass in 1, 2, 3 or 10 values. Variable length parameter lists can be used instead of multiple int declarations. They are declared using the params keyword. Variable length parameters are always passed by value.

  1. static float average(params int[] items)
  2. {
  3. int total = 0;
  4.  
  5. foreach (int value in items)
  6. {
  7. total += value;
  8. }
  9.  
  10. return (total / items.Length);
  11. }
  12.  
  13. Console.WriteLine(average(1,2,3));
  14. Console.WriteLine(average(1,2,3,4,5,6,7,8,9));

This technique can be used to pick up on arguments passed into the program in the Main method:

  1. static void Main(string[] args)

Summary and Conclusions

We have seen how to pass numbers to a method and perform a calculation on them, returning the value back to the method it was called from. We used variables of type int in this example, but you can use any of the defined types, a class, array, struct or any other data type.

Last updated on: Saturday 24th June 2017

Did you Like this Post? Why not Like us on Facebook?

 

Comments
  1. Nirvin M
    Nirvin M

    Wow! This is website is awesome. I bookmarked this page and regularly learning .NET from this site. I congratulate the team...Thank you for wonderful tutorials...

  2. Kunal
    Kunal

    Hi Friends,

    Can anybody please tell how to return more than 1 value from a function (means suppose I pass two int to a function and get three result SUM, MULT, DIV of that values using single function)

    1. Scott
      Scott

      Hi Kunal,

      hopefully you received a timely response to this earlier... but you could use an object (or possibly struct) as your return type. just create a class with meaningful return members and then extract them from the object after the method call.

      You could also potentially use a combination of return value and out variables to accomplish the same thing without a return object.

      hope this helps.

      Regards,
      Scott

  3. Kunal
    Kunal

    Hi Friends,

    Can anybody please tell how to return more than 1 value from a function (means suppose I pass two int to a function and get three result SUM, MULT, DIV of that values using single function).

  4. sanay
    sanay

    Hi
    I found a good example for my method we can pass the aray values inside the method with the help of "param" thanx a lot

    sanjay Vishwakarma

Leave a Reply

Your email address will not be published.