Как вызвать функцию в си шарп
Перейти к содержимому

Как вызвать функцию в си шарп

  • автор:

Урок 43. Функции C#

Сорок третий урок учебника по основам C# посвящен созданию методов, описанных в предыдущей части. В этой статье рассматривается создание методов, возвращающих значение и способных принимать параметры. Иначе их еще называют функциями.

В предыдущей статье были созданы простые методы C# для централизации задач, повышения читаемости и ремонтопригодности кода. Эти методы работали изолированно, поскольку не было возможности передать информацию в функцию и не возвращалось значение по завершении. Хотя это и полезно, большинство создаваемых методов требуют параметров, возвращаемых значений или и того, и другого.

Создание метода, возвращающего значение

Ранее мы создали метод, который получил текущую дату и время и вывел его на консоль в нужном формате. На этом уроке мы создадим метод, который возвращает дату и время, а не выводит его. Можно создать функции, использующие для возвращаемого значения любой тип значения или ссылочный тип. В этом случае форматированные дата и время будут возвращены в виде строки.

Для объявления функции сначала указывается тип возвращаемого значения, за которым следует имя метода и пара скобок (). Код добавляется в блок кода. Поэтому код для объявления нашего пустого примера выглядит следующим образом:

Чтобы вернуть значение вызывающей процедуре, используется команда return, за которой следует значение или объект, подлежащий возврату, как показано ниже:

Теперь можно вызвать функцию. Если вы используете консольное приложение, класс по умолчанию будет называться Program и будет содержать метод Main, а также GetFormattedDate. Чтобы использовать новый, сначала создайте новый программный объект, а затем вызовите его функцию GetFormattedDate, присвоив результат переменной. Это можно контролировать в основном методе, делая окончательный код следующим образом:

Добавление параметров

До сих пор методы, созданные в учебнике, выполняют только одну задачу, и их работа не может быть настроена. Добавляя параметры, можно передавать информацию из вызывающей функции в метод для управления обработкой.

Любое количество параметров может быть добавлено к методу путем объявления каждого параметра в скобках метода, разделенных запятыми. Каждый параметр должен иметь тип данных, объявленный с использованием того же синтаксиса, что и при создании неинициализированной переменной.

Для этого примера мы создадим функцию, которая принимает два параметра, определяющие ширину и высоту прямоугольника. Значения будут умножены, чтобы получить площадь прямоугольника и возвращенное результирующее значение. Во-первых, метод определяется с возвращаемым значением и двумя указанными параметрами. Обратите внимание, что параметры определяются в нижнем регистре верблюда. Это означает, что начальная буква каждого слова в имени пишется с большой буквы, за исключением первого слова, которое является строчным. Это полезное Соглашение для именования переменных и параметров.

Статический метод

В приведенном выше примере был создан новый объект класса Program, чтобы метод мог быть выполнен. Возможно, вы заметили, что метод Main был объявлен иначе, чем метод OutputFormattedDate. В частности, он имеет статический префикс. Это объявляет метод как статический метод, что означает, что ни один объект не должен быть создан до вызова метода. Используя префикс нового метода с тем же статическим ключевым словом, мы можем удалить требование для создания объекта программы.


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегистатьи IT, си шарп, уроки по си шарп, функции, методы

Функции

Функции позволяют вам выделить часть кода программы и вызвать его из других частей программы. Вам может быть трудно повторять части кода во многих местах , поэтому в таких случаях нв помощь приходят функции. В C# их обычно декларируют так:

Чтобы вызвать функцию, вы просто пишете ее имя, открывающуюся скобку, параметры, если они есть, и закрывающуюся скобку. Вот так:

Это пример нашей функции DoStuff():

Первая часть public обозначает область видимости переменной и она является выборным параметром. Если вы его не определяете, то функция будет private. Подробнее об этом позже. Следующий параметр — возвращаемый тип. Если возможен допустимый в C# тип или, как показано здесь, void. Это означает, что функция не возвращает ничего. Также эта функция не имеет параметров, что видно по пустым скобкам за названием функции. Чтобы оживить картину, внесем изменения:

Мы изменили почти все. Функция теперь возвращает целое значение, она принимает два целых параметра и вместо того, чтобы что-то выводить, меняет вычисление и тогда возвращает результат. Это значит, что мы можем добавить два числа из разных мест нашего кода, просто вызвав эту функцию, вместо того, чтобы каждый раз описывать вычисление. Этот маленький пример показывает, что функции помогают сэкономить множество времени и усилий:

Как было сказано, эта функция возвращает значение, которое должна была вычислить. Если декларируется тип возвращаемого значения функции не void, мы сами должны приложить усилия, описав, что именно должна вернуть функция. Вы можете удалить строку с возвращаемым значением из кода и уведите, что сделает программа:

‘AddNumbers(int, int)’: не все части кода возвращают значение

Компилятор напоминает нам, что у нас есть функция, которая ничего не возвращает, хотя мы обещали. И компилятор достаточно умный! Вместо удаления строки, попробуйте что-то вроде этого:

Вы увидите точно такую же ошибку, но почему? Потому что нет гарантии, что наш if-оператор получит значение «true» и строка «return» будет выполнена. Вы можете это исправить, введя в конце кода вторую строку «return».

Это решит созданную нами проблему и продемонстрирует, что в функции может быть не один оператор return. Как только он будет достигнут, транслятор кода покинет функцию. Это означает, что как только результат превысит 10, return 0″, никогда не будет достигнут.

  • Afrikaans
  • Chinese
  • Czech
  • Dutch
  • French
  • Georgian
  • German
  • Indonesian
  • Italian
  • Polish
  • Portuguese
  • Romanian
  • Russian
  • Serbian
  • Spanish
  • Thai
  • Turkish
This article has been deprecated!

This article has been re-organized and updated to better match the rest of the tutorial.

C# Functions Tutorial

In this tutorial we learn how to group sections of our code to be reused in C#.

We cover how to define and use (call) functions, how to add parameters and return values from a function as well as how to pass parameters by reference and out parameters.

What is a function

A function is one or more statements grouped together for reuse throughout our code.

So far, any functionality we wanted in our application was done inside the Main method. When an application becomes bigger and more complex though, we need to separate our code into smaller sections of logic.

We want one section of code to only be responsible for one task, so we separate the sections into functions.

As an example, let’s create some simple functionality:

The example above checks a number to see if it’s odd or even. We can separate all this logic and put it into a function.

But first, let’s see how a function is created.

How to define a function

At it’s most basic, a function consists of a return type, a name, a list of parameters, and at least one statement in it’s body.

A function can return a value when it executes. For example, it can do a mathematical calculation and return the result to us. We need to explicitly tell the compiler which type of value the function will return, even when the function doesn’t return a value.

The parameter list is a list of variables that act as inputs for our function. We can use these parameters inside the function.

The return value is the result of the logic, the value that comes back once the function has finished its execution. As mentioned above, a function doesn’t always need to return a value.

Let’s look at an example of the most basic function.

In the example above, we defined a function called PrintMessage. It’s job is to print a simple message to the console. For now, forget about the static keyword in front of the definition, focus on the rest of the function definition.

Let’s break it down step by step:

  1. When a function doesn’t return a value, we specify its return type as void.
  2. This function doesn’t have any input parameters so there’s nothing inside the parentheses. Even if we don’t have any input parameters, the parentheses must still be there.
  3. Inside the function’s execution block we specify what it must do. In this case it only prints a simple message to the console.

If we run the example above, nothing will happen. The application will run and then exit. The reason is that we’ve defined a function, but we did not use it.

When we define a function, it won’t execute automatically. We have to tell the compiler that we want to use it. This is done in a function call.

We cannot define a function directly inside a namespace. It has to be defined in a class.

How to call (use) a function

To call a function we write it’s name, followed by the parentheses. If our function has any parameters, we specify them between the parentheses.

Let’s call the function that we created in the previous part of this tutorial.

In the example above, we call our function inside the Main() function of the program. When we run the application now, it will execute the function and print the message “Hello World”.

The Console.ReadLine() function is included after the function so that the console stays open and we can see the printed message. If we don’t include it, the application will run, print the message and then immediately close again.

The Main() function is the application’s starting point. Every application must have a Main() function that runs the starting code.

How to add parameters to a function

Parameters act as inputs for our function. The function can use those inputs inside its execution block.

For each parameter that we specify, we have to include it’s type. The parameter is a temporary variable that will be replaced by whatever we input as an argument.

Let’s create a parameter for our function.

In the example above, we create a string variable called Message. In the execution block we put that variable in the Console.WriteLine() function.

What will happen is that any string value we type between the parentheses will go where the Message variable is in the execution block.

In the function call we write the words “Hello World” between the parentheses. The compiler will take the words and insert them wherever our Message variable appears in the function’s execution block.

When we run the application again now, it still prints out the message “Hello World”.

The great thing is we can change the message now at any time.

When we run the example above, the message changes from “Hello World” to “Greetings all”.

The value we give to the parameter is called an argument.

We can even call our function multiple times with different messages.

In the example above, we call the function twice with different arguments to print out the messages we want.

That’s the whole point of a function, to allow us to reuse a section of code without rewriting all the logic.

We can also have multiple input parameters. When we do, we separate each parameter with a comma in the parentheses.

The function’s parameters can also be of different types.

In the function definition above, we have two parameters of different types. In the function call we are required to specify both parameters (without their types).

How to return a value from a function

As mentioned at the start of this tutorial, a function can return a value if it needs to.

We return a value from a function by writing the return keyword, followed by whatever we want to return.

In the example above, we have a simple function that calculates the sum of the first and second parameters and returns the answer.

When we run the example, it doesn’t do anything. The function executed, calculated the sum and returned a value, but we didn’t do anything with the returned value.

We can use the returned value directly, or we can store it into a variable.

In the example above, we call the function directly in the Console.WriteLine() function to print the returned value to the console.

In the example above, we store the returned value in a variable before we print it to the console.

Custom isEvenInt() function

At the start of this tutorial we had some functionality that we wanted to place inside a function. You now know enough about functions to be able to do it yourself.

Try to rewrite the functionality into a function. If you get stuck, see our function below.

The function’s job is to determine if a number is an odd or even number.

Let’s break it down step by step:

  1. We don’t need anything fancy, we can just tell the function to return true if the number is even, or false if the number is odd. So, the return type can be a boolean.
  2. In our parameter list we create a temporary variable called num that will be the number we evaluate to be even or odd.
  3. If the number is even, the function returns true, if the number is odd, it will return false.

Now that we understand the function, let’s run it in our application with a few calls.

In the example above, we call our function directly into the WriteLine() function to print out the results of the logic.

How to pass a parameter by reference

A reference parameter is a reference to a memory location of a variable.

When we pass a parameter by reference, a new storage location in memory is not made, instead we modify the value that already exists in memory (unlike passing a parameter by value which creates and changes a copy).

When declaring a reference parameter we need to specify the ref keyword in front of the type.

In the example above the return type is void, meaning it doesn’t have to return a value. In a normal method we would likely return word1 as a string to do something with.

We don’t need to do that here though because any variable passed into the word1 parameter will be changed to hold the new value.

Think of it as returning the result right into the word1 parameter.

Note that when calling a function with a parameter passed by reference, we must use the ref keyword again.

In the example above, the purpose of the function is to change the value of word1 into the value of word2.

The word we want to change is “World”. We are required to assign it to a variable because that variable will hold the changed value (the “returned” value).

The SwapWord() function didn’t have to be stored in a variable because the value of the parameter a is now the result.

In truth, we don’t pass parameters by reference often, but the functionality exists if we want to use it.

How to use out parameters

When we return from a function, we can only return a single value.

If we need to return multiple values, however, we can use output parameters.

Output parameters are similar to reference parameters, the difference is that you can’t use an out parameter to take a value and use it inside the function.

C# Functions

Summary: in this tutorial, you’ll learn how to make your code reusable by using C# functions.

Introduction to the C# functions

Sometimes, you want to perform the same task multiple times in a program. To do so, you can copy and paste the code into various places. However, doing so makes the program very difficult to maintain.

In programming, we have the Don’t Repeat Yourself (DRY) principle. It means that if you find yourself writing the same statements over and over again, you can turn those statements into a function.

By definition, a function is a reusable named block of code that does one task.

For example, the following defines the SayHi() function that outputs the «Hi» message to the console:

In this function:

  • void keyword indicates that the SayHi function doesn’t return a value.
  • The SayHi identifier is the function name. And you should name the function as descriptive as possible. By convention, the function name should start with a verb (do something specific).
  • A function can have zero or more parameters specified in the parentheses that follow the function name. In this example, the SayHi function has no parameter. We’ll cover the parameters shortly.
  • The block that follows the parentheses is the function body. A function body contains one or more statements.

To use the SayHi() function, you call it like this:

When encountering a function call, the compiler will execute the statement inside that function. In this example, it executes the statement that outputs the «Hi» message.

And you can call the SayHi() function as many times as you want like this:

Passing information to functions

To say hi to someone, you can modify the SayHi() function by adding the name parameter like this:

The name is the input of the SayHi() function. Technically speaking, the name is a parameter of the SayHi() function.

Defining a parameter is like declaring a variable. And you can access the parameter like a variable inside the function.

When calling the SayHi() function, you need to specify a value for the name parameter as follows:

Put it all together.

Parameters vs. arguments

A function parameter is an identifier that you specify in the function definition while a function argument is a value that you pass to the function when calling it.

In the previous example, the name is a parameter of the SayHi() function. When calling the SayHi() function, you pass the literal string «John» to it. This string value is called an argument.

Sometimes, you’ll see the terms parameter and argument are used interchangeably. But it’s important to understand the difference between them.

Returning a value

The SayHi() function doesn’t return any value. Therefore, you use the void keyword. However, if a function returns a value, you need to specify the type of the return value instead.

For example, the following new SayHi() function returns a string:

In this new SayHi() function, we use the string keyword as the return type of the function instead of void . Also, we use the return statement to return a string.

The following code calls the SayHi() function, assigns the return value to the greeting variable, and prints it out:

The reason we return a string from the SayHi() function instead of outputting it directly to the console is that we want to reuse the SayHi() function in other applications such as web applications, not just console applications.

Documenting C# functions with XML comments

The following example defines the CalculateBMI() function that calculates the body mass index based on the weight in kilograms and height in meters:

When calling the CalculateBMI() function, the Visual Studio (or any code editor) shows the function header:

However, if you want it to show more information about the function, you can add comments to the function. like this:

To create a comment section for a function, you enter three forward slashes ( /// ) right before the function header.

The comment of the CalculateBMI function has three main tags: summary , param , and returns .

  • The summary tag contains the function description
  • The param tag describes the parameters
  • The returns tag contains the information of the return value

C# function example

The following program calculates the BMI and displays the corresponding weight status:/

First, define the CalculateBMI() function that returns the BMI based on weight and height:

Next, define the GetWeightStatus() function that returns the weight status based on a BMI:

Then, prompt users to input the height and weight:

After that, call the CalculateBMI() and GetWeightStatus() function to calculate the BMI and weight status:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *