Signup/Sign In
LAST UPDATED: SEPTEMBER 4, 2021

C# Methods

    In C#, a method is a block of code that contains a series of statements to perform certain operations. In a well-written C# code, each method performs only one task. Methods are useful to improve the code reusability by reducing the code duplication. Suppose if we have the same functionality to perform in multiple places, then we can create one method with the required functionality and use it wherever it is required in the application.

    Points to remember for C# methods:

    1. The Main() method name is reserved for the method that begins execution of the program.

    2. We don't use C#'s keywords for method names.

    3. A method must be declared either inside a class or struct by specifying the required parameters.


    Syntax of C# Methods:

    Following is the syntax of defining a method inside a class in C#:

    public class Class_name
    {
        ...
        ...
        <Access_Modifier> <Return_Type> Method_Name(<Parameters>)
        {
            // Method Body
        }
        ...
        ...
    }

    If you look closely at the above syntax, we defined a method inside a class with various components, which are,

    1. Access Modifier: It determines the visibility of a variable or a method from another class. It can be public, private, internal, protected or protected internal.

    2. Return Type: A method may or may not return a value. The return type specifies the data type of the value that the method will return. The return type is void if the method is not returning any values.

    3. Method Name: Method name is case sensitive and should be a unique identifier. It cannot be same as any other identifier declared/defined inside the class.

    4. Parameter List: Enclosed between parentheses after the name of the method, the parameters are used to provide data to the method when the method is called. The parameter list(yes, while declaring a method you can specify the number of parameter that the method will accept) will specify the type, order, and the number of the parameters accepted by the method. It is not necessary for a method to have parameters.

    5. Method Body: Everything that is inside the curly braces { } is the method's body.

    Let's see the very basic example of a user-defined method without parameters.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public void Area()
            {
                Console.WriteLine("Calculating the area of geometric shapes");
            }
    
            public static void Main()
            {
                Program p = new Program();   // creating object
                p.Area();   // calling method
                Console.ReadKey();
            }
        }
    }

    Output:

    Calculating the area of geometric shapes

    In the above program, we have created a basic Area method which will print a fixed output on the console. In the Main() method, we have created the object of the class Program, to call its method Area(), and the Area() method doesn't return anything as the return type is void. Also, this method takes not argument, hence the parentheses is empty.

    Now, let's take an example of a user-defined function with parameters and return type,

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            // Area function with return type int
            public int Area(int a, int b)
            {
                Console.WriteLine("Calculating the area of geometric shapes");
                // returning the result
                return a * b;
            }
            
            public static void Main()
            {
                int result;
                Program p = new Program();
                result = p.Area(20, 30);
                Console.WriteLine("Area of Rectangle is "+result);
                Console.ReadKey();
            }
        }
    }

    Output:

    Calculating the area of geometric shapes
    Area of Rectangle is 600

    In the above program, we have created a parameterized method named Area. The method will return the area for a geometric shape(square or rectangle) and the value will be of type int as the return type is mentioned as int. We have created the object of the class Program to call its Area method, and while calling that method, we have passed two values, 20 and 30 respectively. Hence, the output on console is 20 * 30 = 600.

    Note: If a function expects two arguments(or any number of arguments), then while calling that function you must provide values for all the arguments, else you will get an error. Also, the datatype of the value provided as parameter values should be the same as the method expects. Like in the Area method, it expects two values, both of int type.


    C# Static Methods

    In C#, the static modifier(keyword) makes an attribute non-instantiable, it means the static item can't be instantiated. If the static modifier is applied to a class then that class can't be instantiated using the new keyword.

    If the static modifier is applied to any variable, method or some property of a given class then they can be accessed without creating an object of the class, just by using class_name.property_name or class_name.method_name. We can directly invoke the static methods from the class level without creating an object, and all instances of the class share the same copy of the method and its data.

    Note: The static modifier can be used with classes, methods, properties, operators, events, and constructors, but it can't be used with indexers, finalizers, or types other than classes. We will learn about the static modifier in details in an upcoming tutorial.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static int Area(int a)
            {
                return a * a;
            }
            
            public static void Main()
            {
                // calling the method directly inside the class
                int result = Area(5);
                Console.WriteLine("Area of Square is " + result);
            }
        }
    }

    Output:

    Area of Square is 25

    Let's see another example with static variable and static method,

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static int counter = 10;
            public static void show()
            {
                Console.WriteLine(counter);
            }
    
            public static void Main()
            {
                Program.show();
                Console.WriteLine(Program.counter);
                Program.counter = 20;
                Console.WriteLine(counter);
                Console.ReadLine();
            }
        }
    }

    Output:

    10
    10
    20
    >

    The above program shows that although we can initialize a static field by using another static field which is not yet declared, the results will be undefined until we explicitly assign a value to the static field.


    C# Recursive Method Call

    A recursive method is a method that calls itself. It usually, has the following two specifications:

    1. Recursive method is a method that calls itself to complete the operation.

    2. The recursive method has a parameter(s) and calls itself with new parameter values.

    Following example demonstrates the use of recursion in method implementing the Fibonacci series program.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static int Fibonacci(int n)
            {
                if ((n == 0) || (n == 1))
                {
                    return n;
                }
                else
                {
                    return Fibonacci(n - 1) + Fibonacci(n - 2);
                }
            }
    
            public static void Main()
            {
                for (int i = 0; i < 10; i++)
                {
                    int F = Fibonacci(i);
                    Console.Write(F + " ");
                }
    
                Console.ReadLine();
            }
        }
    }

    Output:

    0 1 1 2 3 5 8 13 21 34


    Conclusion:

    With this, now you can create a class and define class methods to perform different functions. In the examples below, we created class with methods to calculate area of a geographical figure, we also covered the concept of static modifer which provides a special characteristic to methods. In the next tutorial, we will learn more about passing parameter to a method when it is called, with more example where we will create meaningful classes with methods.

    You may also like:

    Subject Matter Expert of C# Programming at Studytonight.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS