C# Method Output Parameters

C# Code Snippets Method Output Parameters
Share:

About

In this code snippet, we’ll see how to use method output parameters in C#.

The output parameter works by passing in a reference of the variable you provide. It is very similar to the ref keyword. You put the out keyword in front of the parameter you want to use as an “output”. The method can still have a data type and return a value as the output parameter isn’t really outputting anything but is rather accessing the variable you passed it via reference.

Let’s look at the code below to see how to use and implement output parameters.

Code:

using System;

namespace OutputParameters
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1 = 50;
            int num2 = 20;

            double result = 0;

            //Using the isDivisible method we will check if the two provided numbers can be divided.
            //If the numbers can be devided the the method will return true and the result will get output via the output parameter. 
            if (isDivisible(num1, num2, out result))
            {
                Console.WriteLine("Result: " + result);
            }
            else
            {
                Console.WriteLine("Numbers not divisible.");
            }
            
            Console.ReadLine();       
        }

        public static bool isDivisible(int num1, int num2, out double outoutParameter)
        {
            bool divisible = false;

            if (num1 != 0 && num2 != 0)
            {
                divisible = true;
                outoutParameter = num1 / num2;
            }
            else
            {
                divisible = false;
                outoutParameter = 0;
            }     

            return divisible;
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger