C# Function Examples

In this chapter you will learn how to create and use function in program.

Example

Qu. Write a program to explain method in C#. Create a static function add() that accept two number from user and returns sum of the number.
Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example1
{
    class calculation
    {
        static int num1, num2, result;
        public static void add()
        {
            Console.Write("Enter number 1st.\t");
            num1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter number 2nd.\t");
            num2 = Convert.ToInt32(Console.ReadLine());

            result = num1 + num2;

            Console.Write("\nAdd = {0}", result);
            Console.ReadLine();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            calculation.add();
        }
    }
}

Output

Enter number 1st.      6
Enter number 2nd.     8
Add = 14
__

Summary

In this chapter you learned how to implement function in C#. In next chapter, some programming questions are given. You must do programming exercise honestly. It will improve your programming skills in implementing method.

 

Share your thought