• Tidak ada hasil yang ditemukan

Chapter 9. Methods

N/A
N/A
Protected

Academic year: 2024

Membagikan "Chapter 9. Methods"

Copied!
57
0
0

Teks penuh

Invoking or invoking a method is basically the process of executing the code of the method, which is placed in its body. When the work of the PrintLogo() method is finished, control of the program is returned to the Main() method – dotted arrow (4).

Parameters in Methods

In some other languages ​​(such as Pascal), calling a method that is declared below the call line is not allowed. If a method is called in the same class where it is declared and implemented, it can be called on a line before the line on which it is declared.

Declaring Methods with Parameters

Imagine that we are in a bookstore and we want to calculate the amount of money that we have to pay for all the books that we have bought. To clarify how the method's execution depends on its input, let's look at another example.

Difference in Declaration of Methods with Multiple Parameters When a method with multiple parameters is declared, we must note that even

Invoking Methods with Parameters

Difference between Parameters and Arguments of a Method Before we continue with this chapter, we must learn how to distinguish

Passing Arguments of a Primitive Type

This does not affect the value of variable numberArg because when invoking this method, the variable numberParam retains a copy of the argument value. Therefore, after invoking the PrintNumber() method in the Main() method, what is printed is the value of numberArg and as can be seen, the value does not change.

Passing Arguments of Reference Type

It is clear that after executing the ModifyArray() method, the array referred to by the variable arrArg does not consist of [1,2,3], but of [5,2,3]. The reason for such a result is the fact that by passing arguments of type reference, only the value of the variable holding the address of the object is copied.

Passing of Expressions as Method Arguments

If the invoked method changes the object to which a reference is passed, this can affect the execution of the code after the method invocation (as we have seen in the example – the PrintArray() method does not print the array that was originally passed). The difference between dealing with primitive and reference type arguments is the way they are passed: primitive types are passed by their values, while objects are passed by reference.

PrintSign(2 + 3);

When calling a method with parameters, we need to be aware of some specific rules, which will be explained in the next subsections. Passing arguments compatible with parameter type We should know that we can only pass arguments that are of compatible type.

Passing of Arguments Compatible with the Parameter Type We must know that we can pass only arguments that are of type compatible

Maintaining the declaration order of the argument types Values ​​passed to the method at the time it is called must be.

Keeping the Declaration Sequence of the Arguments Types Values, that are passed to the method, in the time of its invocation, must be

Variable Number of Arguments (var-args)

Such a call is only possible if we have declared the method in a way such that it accepts a variable number of arguments (var-args). How to declare a method with a variable number of arguments Formally, the declaration of a method with a variable number of arguments.

The method can be called with one, two or more parameters, or without parameters. From the formal definition above of a parameter that allows passing a variable number of arguments through the method call – is actually a name of an array of type . The method call stores the arguments of type or the compatible type that we pass to the method (without regard to their number) in this array.

Position and Declaration of a Method with Variable Arguments A method that has a variable number of its arguments may also have others.

Position and Declaration of a Method with Variable Arguments A method, that has a variable number of its arguments, can also have other

As we can see, the only change is to change the array prices declaration by adding params before decimal[]. Since prices are an array, it can be assumed that we can declare and initialize an array before our method is called. The only thing we need to take into account is that the parameter list element in the method definition, which allows passing a variable number of arguments, must always be placed at the end of the parameter list.

The parameter list element that allows a variable number of arguments to be passed when invoking a method must always be declared at the end of the method's parameter list.

Limitations on the Count for the Variable Arguments

Specifics of Empty Parameter List

Optional Parameters and Named Arguments

As we can see, the C# language allows us to create variations on the same Draw method. If we change the parameter type from a certain position in the parameter list to another type, in C# they count as two absolutely different methods, or more precisely, different variants of a method with the same name. The compiler will accept the code again if we declare two variants of the method, but this time we are going to change the order of the parameters instead of their type.

In the example above, the order of the parameter types is different, and this also makes the signature different.

Overloaded Methods Invocation

The reason this doesn't work is that the compiler tries to convert both integers to appropriate types before passing them to one of the methods called PrintNumbers. There are two possible options – either to convert the first parameter to float and call the method PrintNumbers(float, int) or to convert the second parameter to float and call the method PrintNumbers(int, float). The above code will compile without error, because after the arguments are transformed, it is clearly decided which method we are referring to – PrintNumbers(float, int).

The code from the example will display an error message during the compilation process because there are two methods with the same parameter lists (ie, with the same signature) that return results of different types.

Triangles with Different Size – Example

Triangle.cs using System;

To print each line of the triangle to the keyboard, we need a tool. The last element of the sequence is the number, passed to the method, as the second parameter (the end of the variable). With the second loop, we press the rest of the lines of the triangle that lie below the middle line.

After each iteration, the loop line is decremented by one and passed as the second PrintLine parameter.

Returning a Result from a Method

Declaring a Method that Returns a Result

As can be seen, the result of the area calculation is of type double.

How to Use the Returned Value?

Assigning to a Variable

Usage in Expressions

Using the Returned Value as Method Parameter

Returned Value Type

The Operator "return"

Compatibility of the Result and the Retuning Type

Using an Expression after the Return Operator

Features of the Return Operator The execution of return does two things

Multiple Return Statements

Why Is the Returned Value Type not a Part of the Method Signature?

The reason for this limitation is that the compiler does not know which of the two methods should be called. Type '' already defines a member called 'Add' with the same parameter types. Where is the name of the class in which we tried to declare those methods.

Fahrenheit to Celsius Conversion – Example

TemperatureConverter.cs using System;

Since we're done with this step of our task solution, we decided that we don't need to put the rest of the steps in separate methods, so we'll just implement them in the Main() method of the class. Then we call the ConvertFahrenheitToCelsius() method and store the returned result in the temperature variable. Using the Console.WriteLine() method, we print the message "Your body temperature in degrees Celsius is X", where X is replaced by the temperature value.

The last step we need to make is to check whether the temperature is higher than 37 degrees Celsius or not.

Difference between Two Months – Example

Obviously, to find the length of the period between two months, we need to subtract the number of the starting month from the number of the ending month. We also take into account that if the second month has a number smaller than the number of the first month, then the user most likely assumed that the second month is not in the current year, but in the next. Therefore, if the difference between the two months is negative, we must add 12 to it - the length of the year in months and thus determine the length of the given period.

Finally, in the Main() method we call the SayPeriod() method, with numbers entered for the beginning and end of the period.

Input Data Validation – Example

If the value is not within the range of [м…м2], the program reports an error. Later in the "Exception Handling" chapter, we will discuss in detail how to report when an error occurs. This is generally incorrect behavior and we will learn how to avoid it in the chapter "High Quality Code", section "What should a method do".

We know that the hours are in the range from 0 to 23 inclusive, and the minutes from 0 to 59 inclusive respectively.

DataValidation.cs using System;

We believe that getting the input data and printing the output messages will no longer be a problem, so we will focus on the input data validation, i.e. since we are done with the most complicated part of the task, we declare the Main() method. After saving the result and telling us whether the input data is valid or not, in the variable isValidTime we use the conditional statement if, dealing with the last problem for the given task: printing the information to the user, or the input is valid or not.

In the second part of the conditional statement, we print that the input time was invalid – "Wrong time!".

Sorting – Example

One of the easiest ways to do this is to use the so-called "selection sort" algorithm. The sorted part is on the left side of the array, while the unsorted part is on the right side. For each step of the algorithm, the sorted part expands to the right by one element and the unsorted part shrinks by one element from its left part.

So this step is repeated until the unsorted part of the array reaches a length of 0, i.e.

SortingEngine.cs using System;

Best Practices when Using Methods

It is not correct for the methods to return incorrect or unusual results when they have received invalid input data. A method must have as few dependencies as possible on the class in which the method is declared and on other methods and classes. This means that the method must do its work using the data passed to it as parameters, but not data that can be accessed elsewhere.

To do this, the logic implemented in the method is divided by functionality into several smaller sub-methods.

Exercises

Solutions and Guidelines

Referensi

Dokumen terkait