Пример функции си шарп

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:

void SayHi( ) < Console.WriteLine("Hi"); >Code language: C# (cs)
  • 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:

Читайте также:  Тег FORM

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:

void SayHi( ) < Console.WriteLine("Hi"); > SayHi(); SayHi(); SayHi();Code language: C# (cs)
Hi Hi HiCode language: C# (cs)

Passing information to functions

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

void SayHi(string name) < Console.WriteLine($"Hi "); >Code language: C# (cs)

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:

SayHi("John");Code language: C# (cs)
Hi JohnCode language: C# (cs)
void SayHi(string name) < Console.WriteLine($"Hi "); > SayHi("John");Code language: C# (cs)

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:

string SayHi(string name) < return $"Hi "; >Code language: C# (cs)

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:

string SayHi(string name) < return $"Hi "; > string greeting = SayHi("John"); Console.WriteLine(greeting);Code language: C# (cs)
Hi JohnCode language: C# (cs)

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:

double CalculateBMI(double weight, double height) < return weight / (height * height); >Code language: C# (cs)

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:

/// /// Calculate the body mass index (BMI) based on weight in kg and height in meter ///  /// /// The weight in kilogram ///  /// /// The height in meter ///  /// /// The body mass index ///  double CalculateBMI(double weight, double height) < return weight / (height * height); >Code language: C# (cs)

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:/

/// /// Calculate the body mass index (BMI) based on weight in kg and height in meter ///  /// /// The weight in kilogram ///  /// /// The height in meter ///  /// /// The body mass index ///  double CalculateBMI(double weight, double height) < return weight / (height * height); > /// /// Get the weight status based on the Body Mass Index (BMI) ///  /// ///The body mass index ///  /// A text string that represents the weight status /// ///  string GetWeightStatus(double bmi) < string weightStatus = ""; switch (bmi) < case < 18.5: weightStatus = "Underweight"; break; case >= 18.5 and 24.9: weightStatus = "Healthy Weight"; break; case >= 25 and 29.9: weightStatus = "Overweight"; break; case > 30: weightStatus = "Obesity"; break; > return weightStatus; > // main program Console.WriteLine("Body Mass Index (BMI) Calculation"); Console.WriteLine("Enter a weight (kg):"); var weight = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter a height (m):"); var height = Convert.ToDouble(Console.ReadLine()); double bmi = CalculateBMI(weight, height); string weightStatus = GetWeightStatus(bmi); Console.WriteLine($"BMI: 0.#>"); Console.WriteLine($"Weight status: ");Code language: C# (cs)

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

/// /// Calculate the body mass index (BMI) based on weight in kg and height in meter ///  /// /// The weight in kilogram ///  /// /// The height in meter ///  /// /// The body mass index ///  double CalculateBMI(double weight, double height) < return weight / (height * height); >Code language: C# (cs)

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

 /// /// Get the weight status based on the Body Mass Index (BMI) ///  /// ///The body mass index ///  /// A text string that represents the weight status /// ///  string GetWeightStatus(double bmi) < string weightStatus = ""; switch (bmi) < case < 18.5: weightStatus = "Underweight"; break; case >= 18.5 and 24.9: weightStatus = "Healthy Weight"; break; case >= 25 and 29.9: weightStatus = "Overweight"; break; case > 30: weightStatus = "Obesity"; break; > return weightStatus; >Code language: C# (cs)

Then, prompt users to input the height and weight:

 Console.WriteLine("Body Mass Index (BMI) Calculation"); Console.WriteLine("Enter a weight (kg):"); var weight = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter a height (m):"); var height = Convert.ToDouble(Console.ReadLine());Code language: C# (cs)

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

double bmi = CalculateBMI(weight, height); string weightStatus = GetWeightStatus(bmi);Code language: C# (cs)
Console.WriteLine($"BMI: 0.#>"); Console.WriteLine($"Weight status: ");Code language: C# (cs)

Summary

  • A function is a reusable named block of code that does one task.
  • A function can have zero or more parameters and an optional return value.
  • Use the return statement to return a value from a function.
  • Use XML comments to document a function.

Источник

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

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

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

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

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

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

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

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

static void Main(string[] args) < Program p = new Program(); string outputDate = p.GetFormattedDate(); Console.WriteLine(outputDate); // Outputs "06/11/2019" >string GetFormattedDate() < DateTime theDate = DateTime.Now; return theDate.ToString("dd/MM/yyyy"); >

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

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

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

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

int GetArea(int rectHeight, int rectWidth) < return rectHeight * rectWidth; >Теперь можно вызвать метод с указанными значениями параметров или аргументами: static void Main(string[] args) < Program p = new Program(); int area = p.GetArea(10, 5); Console.WriteLine(area); // "50" >int GetArea(int rectHeight, int rectWidth)

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

static void Main(string[] args) < int area = GetArea(10, 5); Console.WriteLine(area); // "50" >static int GetArea(int rectHeight, int rectWidth)

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

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

Источник

Оцените статью