Loading, please wait...

A to Z Full Forms and Acronyms

Different types of method in c#

Sep 04, 2019 Methods in C#, C#, .Net, CSharp, 12799 Views
This article will explain different types of method in c#.

What is the method?

The method is a block of code that contains a series of the statement.

Different types of methods in C# programming.

  1. Parameter less method
  2. Parameterized method
  3. Parameter and return method
  4. Call by value method
  5. Reference method
  6. Out parameter method
  7. Method overriding
  8. Method overloading
  9. Method hiding
  10. Abstract method
  11. Virtual method
  12. Static method

Parameter less method: A method which does not have any parameter is called parameter less method. It is a block of code with the statement.

using System;
 
namespace MethodExamples
{
    class ParameterLessMethod
    {
        protected void Message()
        {
            Console.WriteLine("Hello World!");
        }
 
        static void Main()
        {
            var p = new ParameterLessMethod();
            p.Message();
            Console.ReadLine();
        }
    }
}

Parameterized method: A method which contains at least one or more parameter is called a parameterized method.

using System;
 
namespace MethodExamples
{
    class ParameterMethod
    {
        public void PrintMessage(string message)
        {
            Console.WriteLine("Hello " + message);
        }
 
        static void Main()
        {
            var p = new ParameterMethod();
            p.PrintMessage("Farhan Ahmed");
            Console.ReadLine();
        }
    }
}

Parameter and return method: A method that does not return any value specifies void type as a return type.

using System;
 
namespace MethodExamples
{
    class ParameterAndReturnMethod
    {
        protected int MethodValue(int value)
        {
            Console.WriteLine("Entered value is:"+value);
            return value;
        }
 
        static void Main()
        {
            var p = new ParameterAndReturnMethod();
            p.MethodValue(15);
            Console.ReadLine();
        }
    }
}

Call by value method: Value type parameters are that pass a copy of the original value to the method rather than reference. It does not change or modify the original value. A change made in passed value does not alter the actual value. Here is the example of the call by value method.

using System;
 
namespace MethodExamples
{
    class CallByValueMethod
    {
        public void ShowValue(int value)
        {
            value *= value;
            Console.WriteLine("Value calling method:" + value);             
        }
 
        static void Main(string[] args)
        {
            int value = 10;
            var p = new CallByValueMethod();
            Console.WriteLine("Value before calling method:"+value);
            p.ShowValue(value);
            Console.WriteLine("Value after calling method:" + value);
            Console.ReadLine();
        }
    }
}

Reference method:  The ref keyword is used to pass and return the reference value. Any value change that passed as a reference also changes and reflect it.

using System;
 
namespace MethodExamples
{
    class CallByReferenceMethod
    {
        protected void PrintNumber(ref int number)
        {
            number *= number;
            Console.WriteLine("Value of reference method: " + number);
        }
 
        static void Main()
        {
            int number = 100;
            var p = new CallByReferenceMethod();
            Console.WriteLine("Value before reference method called: " + number);
            p.PrintNumber(ref number);
            Console.WriteLine("Reflected value afrter method called: " + number);
            Console.ReadLine();
        }
    }
}

Out parameter method: The out keyword is used to pass the argument as out parameter. It is same as a reference type, except that it does not require initialization before it passes to the method. It is useful when we need to return multiple values in a method.

using System;
 
namespace MethodExamples
{
    class OutParameterMethod
    {
        protected void PrintNumber(out int number)
        {
            int squre = 10;
            number = squre;
            number *= number;
            Console.WriteLine("Value when calling out parameter: " + number);
        }
        static void Main()
        {
            int number = 20;
            var p = new OutParameterMethod();
            Console.WriteLine("Value befor calling out parameter method: " + number);
            p.PrintNumber(out number);
            Console.WriteLine("Value after calling out parameter method: " + number);
            Console.ReadLine();
        }
    }
}

What is the extension method?

An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types.

using System;
 
namespace MethodExamples
{
    class ExtentionMethod
    {
        static void Main()
        {
            int number;
 
            Console.WriteLine("Enter numer");
            number = Convert.ToInt32(Console.ReadLine());
            bool result = number.IsEven();
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
 
    public static class Helper
    {
        public static bool IsEven(this int number)
        {
            return (number%2==0);
        }
    }
}

What is the anonymous method?

An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn't require the name and return type.

using System;
 
namespace MethodExamples
{
    class AnonymousMethod
    {
        public delegate void Print(int value);
 
        static void Main()
        {
            Print print = delegate (int val) 
            {
                Console.WriteLine("Inside Anonymous method. Value: {0}", val);
            };
            print(100);
 
            Console.ReadLine();
        }
    }
}

What is method overloading?

A method with the same name but a different signature is called method overloading.

using System;
 
namespace MethodExamples
{
    class MethodOverloading
    {
        static void Main()
        {
            var demo = new Demo();
            int firstTotal= demo.Add(10, 20);
            int secondTotal = demo.Add(10, 20, 30);
            double thirdTotal= demo.Add(10.5, 20.5);
 
            Console.WriteLine("Total:{0}",firstTotal);
            Console.WriteLine("Second Total:{0}",secondTotal);
            Console.WriteLine("Third Total:{0}", thirdTotal);
 
            Console.ReadLine();
        }
    }
 
    public class Demo
    {
        public int Add(int valueOne, int valueTwo)
        {
            return valueOne + valueTwo;
        }
 
        public int Add(int valueOne, int valueTwo, int valueThree)
        {
            return valueOne + valueTwo + valueThree;
        }
 
        public double Add(double valueOne, double valueTwo)
        {
            return valueOne + valueTwo;
        }
    }
}

What are the different ways a method can be overloaded?

Methods can be overloaded using different data types for the parameter, different order of parameters, and different number of parameters

What is method overriding?

A method with the same name and the same parameters is called method overriding.

using System;
 
namespace MethodExamples
{
    class MethodOverriding
    {
        static void Main()
        {
            var employee = new Employee();
            employee.PrintFullName();
            Console.WriteLine("------------");
            var contactEmployee = new ContactEmployee();
            contactEmployee.PrintFullName();
            Console.ReadLine();
        }
    }
 
    public class Employee
    {
        public string firstName { get; set;}
        public string lastName { get; set; }
       
        public virtual void PrintFullName()
        {
            Console.WriteLine("Please enter first name:");
            firstName = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Please enter last name:");
            lastName = Convert.ToString(Console.ReadLine());
 
            Console.WriteLine("FullName:"+ firstName +" "+ lastName);
        }
    }
 
    public class ContactEmployee:Employee
    {
        public override void PrintFullName()
        {
            base.PrintFullName();
        }
    }
}

What is method hiding?

A method with the same name and same parameters hide the method of the base class by using the new key word is called method hiding.

using System;
 
namespace MethodExamples
{
    class MethodHiding
    {
        static void Main()
        {
            var customer = new Customer();
            customer.FullName();
            Console.WriteLine("----------");
            var premiumCustomer = new PremiumCustomer();
            premiumCustomer.FullName();
 
            Console.ReadLine();
 
        }
    }
 
    public class Customer
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
 
        public void FullName()
        {
            Console.WriteLine("Enter first name");
            firstName = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Enter last name");
            lastName = Convert.ToString(Console.ReadLine());
 
            Console.WriteLine("Full Name:" + firstName + " " + lastName);
        }
    }
 
    public class PremiumCustomer:Customer
    {
        public string middleName { get; set; }
 
        public new void FullName()
        {
            Console.WriteLine("Enter first name");
            firstName = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Enter middle name");
            middleName = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Enter last name");
            lastName = Convert.ToString(Console.ReadLine());
 
            Console.WriteLine("Full Name:" + firstName + " " +middleName +" " + lastName);
        }
    }
}

What are abstract methods?

A method with abstract modifier indicates that the method is an abstract method. Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MethodExamples
{
    public abstract class AbstractMethod
    {
        public abstract void MyAbstractMethod();
    }
}

Features of the abstract method

An abstract method is implicitly a virtual method.

Abstract method declarations are only permitted in abstract classes.

An abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature.

The implementation is provided by a method override, which is a member of a non-abstract class.

It is an error to use the static or virtual modifiers in an abstract method declaration.

 

What is a virtual method?

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using the override keyword.

using System;
 
namespace MethodExamples
{
    public class VirtualMethod
    {
        public virtual string Message(string msg)
        {
            return "Hello" + msg;
        }
    }
 
    public class myClass : VirtualMethod
    {
        public override string Message(string msg)
        {
            return base.Message(msg);
        }
    }
 
    public class program
    {
        static void Main()
        {
            var p = new VirtualMethod();
            string name= p.Message("Farhan Ahmed");
 
            var p1 = new myClass();
            string name1= p1.Message("Rahul Sharma");
 
            Console.WriteLine(name);
            Console.WriteLine(name1);
 
            Console.ReadLine();
        }
    }
 
}

What is the difference between the virtual method and abstract method?

Virtual Method: The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using the override keyword.

Abstract Method: An Abstract method does not have an implementation. It resides inside the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used

What is the static method?

The static keyword is used to create a static method. A static method is a method that can be called without creating an object of the class. It is referenced by the class name itself or reference to the Object of that class.

using System;
 
namespace MethodExamples
{
    static class StaticMethod
    {
        public static void PrintValue(int value)
        {
            Console.WriteLine("The Value is: " + value);
        }
    }
 
    public class StaticExample
    {
        static void Main()
        {
            StaticMethod.PrintValue(100);
            Console.ReadLine();
        }
    }
}
A to Z Full Forms and Acronyms