Methods in C#

Methods in C# is a code  block containing of statements.Methods are declared  within class or struct by specifying the access  level, the name of the method, the return value and any method parameters. To use  a method, you need to define the method and call the method. Syntax for defining a method in C# are:
Access Specifier(public or privateReturn Type Method Name(Parameter List)
{
    Body  Methods
{


Example:
  • In C# if the method is not returning any values, then the return type is void.
public void NameMethods(int number, int value)
{

} 
  • This methods return the value! 
class Methods
{
    public int NameMethods(int value1, int value2)
    {
       return value1 * value2;
    }
}
  
















Calling Methods in C#

In C# you can call method using  the name of the method.

Example:

namespace Methods
{
    class Program
    {
        static void Main(string[] args)
        {
            nMethods M = new nMethods();
            Console.Write("\nValue1 = ");
            int A;
            A = int.Parse(Console.ReadLine());
            Console.Write("\nValue2 = ");
            int B;
            B = int.Parse(Console.ReadLine());           
            int C;
            C = M.NameMethod(A, B);
            Console.WriteLine("\nResult: "+C);
            Console.ReadLine();
        }

        class nMethods
        {
            public int NameMethod(int value1, int value2)
            {
                return value1 * value2;
            }
        }

    }
}

Example Methods in C#




No comments:

Post a Comment