Lesson 7.2

C# Functions or Methods with Programming Example


What is method or function in c#?
How to define and call a method?
Programming Example

What is method or function in c#?

A method is a block of code which contains series of execution statement. It is a basic building block of object oriented programming. In C#, main method is a starting point of execution. If a method doesn’t return anything it is void method or if it returns integer then it is int method.

How to define a method?

public void method_name()

public int method_name()
return integral_value;

public string method_name()
return string_value;

How to call a method?

You can call a method directly with its name if method is in the same class. If method is different class then you can call followed by its object name. You can better understand it by following programming example:

Programming Example:

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

namespace function_or_methods
    class Program
        string name, city, country;
        //Main Method
        static void Main(string[] args)
            Program p = new Program();

        //Creating Method
        public void GetDetails()
            Console.Write("Enter Your Name : ");
            name = Console.ReadLine();

            Console.Write("Enter Your City : ");
            city = Console.ReadLine();

            Console.Write("Enter Your Country : ");
            country = Console.ReadLine();

        //Creating Method
        public void PrintDetails()
            Console.WriteLine("\n\n********Your Details**********");
            Console.WriteLine("Your Name is " + name);
            Console.WriteLine("Your City is " + city);
            Console.WriteLine("Your Country is " + country);


Enter Your Name : Mark
Enter Your City : California
Enter Your Country : USA

********Your Details**********
Your Name is Mark
Your City is California
Your Country is USA

In the above example we have created 2 method GetDetails() and PrintDetails(). GetDetails() function accepts some user input and store in a variable. The PrintDetails() function access the variable values and print on console.


In this chapter you have learned what method is and how to declare and call it. In the next chapter you will learn how to pass parameter in a method.