C# Method With Custom Return Type Example

C# Method With Custom Return Type Example
C# Method With Custom Return Type Example

The most common C# method return type is void.  If your method is not going to return anything, then simply you can select void as your return type.  But in some cases, you want a custom return type like string, int, array, etc then  you have to explicitly assign the return type to the method.

As you know, we have ability to pass custom type parameters and keeping this in mind, we are going to work over an example.  In this example, we will take 2 numbers, which will be of type integer.  We will call our custom method Add to return the sum of those numbers, which will be of type integer.  The C# method with custom return type sample code is given below:

 

using System;

namespace MyHelloWorld
{   
    class Program
    {
        static void Main(string[] args)
        {

            int sum = Add(10, 20);
            Console.WriteLine("The sum of 2 numbers is {0}.", sum);
        }

        public static int Add(int n1, int n2)
        {
            int total = n1 + n2;
            return total;
        }
    }
}

Output

The sum of 2 numbers is 30.
Press any key to continue . . .