Calling method or function (C#)

In this chapter you will learn:
  • How to declare and call method in Main method?
  • How to declare and call static method in Main method?
  • How to implement method or function in programming?

After creating function, you need to call it in Main() method to execute. In order to call method, you need to create object of containing class, then followed bydot(.) operator you can call the method. If method is static, then there is no need to create object and you can directly call it followed by class name.

 

Programming Examples

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Declaring_Method
{
    class Program
    {
        string name, city;
        int age;

        public void acceptdetails()
        {
            Console.Write("\nEnter your name:\t");
            name = Console.ReadLine();

            Console.Write("\nEnter Your City:\t");
            city = Console.ReadLine();

            Console.Write("\nEnter your age:\t\t");
            age = Convert.ToInt32(Console.ReadLine());
        }

        public void printdetails()
        {
            Console.Write("\n\n====================");
            Console.Write("\nName:\t" + name);
            Console.Write("\nCity:\t" + city);
            Console.Write("\nAge:\t" + age);
            Console.Write("\n====================\n");
        }

        static void Main(string[] args)
        {
            //creating object of class Program
            Program p = new Program();
            p.acceptdetails(); // Calling method
            p.printdetails(); // Calling method
            Console.ReadLine();
        }
    }
}

Output
Enter your name:     Steven Clark
Enter Your City:      California
Enter your age:       47

===================================
Name:   Steven Clark
City:     California
Age:     47
================================== __
If method is declared static then you can directly call the method without creating object of containing class.

Programming Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calling_method
{
    class print
    {
        public static void printname()
        {
            Console.WriteLine("Steven Clark");
            Console.ReadLine();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // call directly static method with class name
            print.printname();
        }
    }
}

Output
Steven Clark
__

Summary

In this chapter you learned about how to call method or function in main method. You also learned how to use static method in C sharp programming. In next chapter you will learn more about how to use static method and variables.

More Articles

 

Share your thought