C#. The concept of the method. Examples of methods in classes. Return from method. The return statement. Methods without parameters. The void keyword




The concept of the method. Examples of methods in classes. Return from method. The return statement. Methods without parameters. The void keyword


Contents


Search other websites:

1. What is a method in class? Method definition in class

Method (function) is a fragment of a subroutine that has a name. By this name, you can call a subroutine (method) one or several times. Instead of the name will be used the body of the subroutine (method). It is advisable to give the name of the method so that it is easy to recognize its function in the program.

In addition to data (variables), classes can contain methods. Methods do some operations on the data (some work). In many cases, methods represent access to class data. Using class methods, the class interacts with other parts of the program or other classes.

Methods complement the class with additional functionality. As a rule, each method performs one function.

 

2. What names are forbidden for methods?

The method name can be any one that follows the rules for using identifiers in C#. However, not all names can be used as a method name.

As a method name it is forbidden to set:

  • the name Main().This is the name of the entry point to a C # program, that is, the program starts from the Main() method. This name is reserved;
  • C# keyword names.

 

3. The general form of the method definition in the class

In general, the implementation of a method in a class has the following form:

access return_type MethodName(parameters_list)
{
    // body of method
    // ...
}

where

  • MethodName – method name, which is declared. By this name, you can call a method from a class or program. When calling a method, the parameters of the method that it receives are required;
  • access – modifier that determines access to the method from different parts of the program. The access modifier can be private, protected, public. The access modifier may be missing, in which case the method is considered as private;
  • return_type – the type returned by the method. If the method does not return a value, the void type is specified;
  • parameter_list – the parameter list that the method receives. The method may have no parameters. In this case, nothing is indicated in brackets.

 

4. What is the purpose of the return statement in the method body?

The ‘return’ statement is used to return a value from a method. If the method returns some value, the call to the return operator is mandatory.
The return statement has two forms. The first form is used when the method returns a value. The second form, when the method does not return a value, that is, returns the type ‘void’.
The first form of the return statement is as follows:

return value;

where value is the value returned by the method. The value type must be compatible with the type that the method returns.
The second form is used when the method does not return a value (void). In this case, the return statement is as follows

return;

In a method that does not return a value, it is not necessary to specify the return statement.

 

5. Examples of methods in classes

Example 1. The example implements the class DemoString. In class are declared:

  • internal variable s of string type, which is a string;
  • constructor of class without parameters. It initializes the string s with an empty value;
  • constructor of class with a parameter that initializes the string s;
  • the IsLetter() method, which determines whether there is a character c in the string s. The character c is specified by the input parameter of the method. The method returns the value of the logical type bool;
  • the Reverse() method, which accepts the input string s and returns the reverse value of this string.

Class implementation text is as follows:

// class that implements string processing
class DemoString
{
    // class methods
    // determines whether there is a character c in string s
    public bool IsLetter(char c, string s)
    {
        for (int i = 0; i < s.Length; i++)
            if (s[i] == c) return true;
                return false;
    }

    // method that returns the reverse string s: "abcd" => "dcba"
    public string Reverse(string s)
    {
        string s2 = "";
        int len = s.Length;

        for (int i = 0; i < len; i++)
            s2 += s[len - i - 1];

        return s2;
    }
}

The use of the DemoString class can be as follows:

DemoString ds = new DemoString();
string s2;
s2 = ds.Reverse("abcde"); // s2 = "edcba"
bool f = ds.IsLetter('p', "bestprog.net"); // f = True

Example 2. A Triangle class is declared that contains:

  • three internal variables with the names a, b, c;
  • a parameterized class constructor that takes three parameters;
  • an internal method of the class GetArea(), defining the area of the triangle along its sides a, b, c. The method does not receive parameters. The method returns the area of a triangle or 0, if a triangle cannot be built along the sides of a, b, c;
  • the internal class method IsTriangle() without parameters. The method determines whether it is possible to construct a triangle along the three sides a, b, c: the sum of any two sides must be greater than the third side. The method returns a boolean value of type bool.

The class declaration text is as follows:

// class that describes a triangle on the basis of three sides a, b, c
class Triangle
{
    double a, b, c; // sides of a triangle

    // constructor
    public Triangle(double _a, double _b, double _c)
    {
        // call internal class method from constructor
        if (!IsTriangle()) return;

        a = _a;
        b = _b;
        c = _c;
    }

    // class method that defines the area of a triangle
    public double GetArea()
    {
        double p,s;
        // call internal method from GetArea() method, checking
        if (!IsTriangle()) return 0.0;

        p = (a + b + c) / 2.0;
        s = Math.Sqrt(p * (p - a) * (p - b) * (p - c));
        return s;
    }

    // method of class that determines whether a triangle can be constructed from given a, b, c
    public bool IsTriangle()
    {
        if ((a + b) < c) return false;
        if ((b + c) < a) return false;
        if ((a + c) < b) return false;
        return true;
    }
}

Using the Triangle class and calling class methods can be as follows:

// the use of Triangle class and its methods
Triangle tr1 = new Triangle(5, 6, 3);
Triangle tr2;
tr2 = new Triangle(7, 7, 7);

double area;
area = tr1.GetArea(); // area = 7.483314

bool isTriangle = tr2.IsTriangle(); // isTriangle = true
area = tr2.GetArea(); // area = 21.217622

 

6. Arguments and formal parameters of the method

Arguments of method are values that are passed to a method during a call to this method from another method or program code.
The formal parameters of a method are variables that are obtained by the method as parameters and are used in this method. The formal parameters of the method are described in parentheses. Formal parameters take values from arguments when calling a method.

For example. Let a method be set that finds the sum of digits of an integer d, which is the input parameter

// method that returns the sum of digits of number d
public int Sum(int d) // d - formal parameter
{
    int t = d;
    int sum;

    if (t < 0) t = -t;

    sum = 0;
    while (t > 0)
    {
        sum = sum + t % 10;
        t = t / 10;
    }

    return sum;
}

When such a method is called, it is passed an argument x, the value of which is equal to -2398. This argument is passed to the formal parameter d in the Sum() method.

int x = -2398;
int sum;
sum = Sum(x); // x - argument of method Sum(), sum = 22 = 2+3+9+8

 

7. How are the parameters passed into the method? Syntax of the description of method parameters

Any method can receive parameters. Method accept parameters to process them. Method parameters are set in brackets, separated by commas. The general form of the list consisting of N parameters of the method is:

type1 param1, type2 param2, ..., typeN paramN

The general form of the method that receives N parameters is:

return_type MethodName(type1 param1, type2 param2, ..., typeN paramN)
{
    // ...
}

where

  • return_type – the type that is returned by the MethodName() method;
  • type1, type2, … typeN – parameter types with the names param1, param2, …, paramN.

 

8. Using the void keyword in method parameters

If the method does not receive any parameters, the method declaration looks like this:

return_type MethodName()
{
    // ...
}

where return_type – a type that returns a method named MethodName().

For example. A method is declared that returns the number Pi.

// method without parameters
double Pi()
{
    return 3.14159265358979323846;
}

If the method returns nothing, the word void is specified instead of the type.

void MethodName(parameters_list)
{
    // ...
}

where parameter_list is a list of method parameters with the name MethodName that it receives.

If the method does not return and does not receive parameters, then the general form of such a method is as follows:

void MethodName()
{
    // ...
}

Example. A method is declared that does not receive or return anything. In the body of the method, the message “Hello world!” is displayed for console applications.

// a method that does not receive or return parameters
void Hello()
{
    Console.WriteLine("Hello world!");
}

 

9. What does the term “inaccessible code” mean in a method?

Inaccessible code is part of the method code that will never be executed. Unavailable code is a programmer’s mistake. If there is inaccessible code in the method, then the compiler shows a warning message of appropriate content.

For example. Below is a method in which there is unavailable (unused) code.

// method that contains unused code
bool More5(int n)
{
    if (n > 5) return true;
    else return false;

    // unused code
    return true; // this statement will never be executed
}

 

10. An example demonstrating various ways to return an instance of a class from a method

The example shows various ways to return a class object from a method. In this example, you can develop your own methods that return the current instance of the class.

Defined class Complex, that implements a complex number. The class declares:

  • two hidden variables real and imag;
  • two constructors;
  • the GetRI() method, which returns the value of the internal variables real and imag as out-parameters;
  • the SetRI() method, which with the help of parameters sets new values of internal variables real, imag;
  • a GetComplex() method that returns the current object (instance) of the Complex class using the return operator;
  • method GetComplex2() that returns the current object (instance) of the class as an out parameter.

In another Program class, the main() function demonstrates the use of the Complex class and the methods GetComplex(), GetComplex2(). Also, the Program class declares the GetComplex3() method, which returns an instance of the Complex class.

The text of the entire program module created using the Console Application template is as follows

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

namespace ConsoleApp6
{
    // class implementing a complex number
    class Complex
    {
        // internal variables
        private double real; // real part
        private double imag; // imaginary part

        // constructors
        public Complex()
        {
            real = imag = 0;
        }

        public Complex(double _real, double _imag)
        {
            real = _real;
            imag = _imag;
        }

        // access methods
        // get the values of real, imag
        public void GetRI(out double _real, out double _imag)
        {
            _real = real;
            _imag = imag;
        }

        // set a new values to real and imag
        public void SetRI(double _real, double _imag)
        {
            real = _real;
            imag = _imag;
        }

        // method that returns the current instance (object) of the class Class
        public Complex GetComplex()
        {
            return this;
        }

        // method that returns an object of the class Complex as an out-parameter
        public void GetComplex2(out Complex _cmp)
        {
            Complex cmp = new Complex(real, imag); // create the object
            _cmp = cmp;
        }
    }

    class Program
    {
        // method of class Program, returning an object (instance) of class Complex
        public Complex GetComplex3(double _real, double _imag)
        {
            Complex comp = new Complex();
            comp.SetRI(_real, _imag);
            return comp;
        }

        static void Main(string[] args)
        {
            // use of methods GetComplex() and GetComplex2() of class Complex
            Complex c = new Complex(3, 5); // create an instance of a class
            double i, r;

            // returning an object using the GetComplex() method
            Complex c2; // declare a reference to the class Complex
            c2 = c.GetComplex();

            // checking
            c2.GetRI(out i, out r); // i=3, r=5

            Console.WriteLine("Method GetComplex():");
            Console.WriteLine("i = {0}", i);
            Console.WriteLine("r = {0}", r);

            // return an instance of the Complex class as an out parameter
            Complex c3; // reference to the Complex class

            c.GetComplex2(out c3); // return object of class Complex

            // checking
            c3.GetRI(out i, out r); // i=3, r=5

            Console.WriteLine("Method GetComplex2():");
            Console.WriteLine("i = {0}", i);
            Console.WriteLine("r = {0}", r);

            Console.ReadKey();
        }
    }
}

From the above example, it is clear that the return of an object of the Complex class is demonstrated using three methods (methods):

  • return of an instance of the current class by the operator return – the method GetComplex() of the Complex class;
  • returning an instance of the Complex class using an out-parameter the method GetComplex2() of the Complex class;
  • returning an instance of the Complex class from a method of another class – the GetComplex3() method of the Program class.

As a result of the program execution the following result will be displayed

Method GetComplex():
i=1
r=5

Method GetComplex2():
i=3
r=5

 


Related topics