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
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Example1
  7. {
  8. class calculation
  9. {
  10. static int num1, num2, result;
  11. public static void add()
  12. {
  13. Console.Write("Enter number 1st.\t");
  14. num1 = Convert.ToInt32(Console.ReadLine());
  15.  
  16. Console.Write("Enter number 2nd.\t");
  17. num2 = Convert.ToInt32(Console.ReadLine());
  18.  
  19. result = num1 + num2;
  20.  
  21. Console.Write("\nAdd = {0}", result);
  22. Console.ReadLine();
  23. }
  24. }
  25. class Program
  26. {
  27. static void Main(string[] args)
  28. {
  29. calculation.add();
  30. }
  31. }
  32. }

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