Основные операторы си шарп

Операторы в C#

Операторы — это символы, которые используются для выполнения операций с операндами. Операндами могут быть переменные и/или константы.

Например, в выражении 2 + 3 , + — это оператор, который используется для выполнения операции сложения, а 2 и 3 — операнды.

Операторы используются для управления переменными и их значениями в программе. C# поддерживает ряд операторов, разделенных по типам выполняемых ими операций.

Простой оператор присваивания

Основной оператор присваивания = используется для присвоения значений переменным.

Здесь переменной x присваивается значение 50.05.

Пример 1. Используем простой оператор присваивания

using System; namespace Operator < class AssignmentOperator < public static void Main(string[] args) < int firstNumber, secondNumber; // Присваиваем переменной значение константы firstNumber = 10; Console.WriteLine("Значение firstNumber = ", firstNumber); // Присваиваем переменной значение другой переменной secondNumber = firstNumber; Console.WriteLine("Значение secondNumber = ", secondNumber); > > > 
Значение firstNumber = 10
Значение secondNumber = 10

Вы могли заметить в примере фигурные скобки <> . Такой метод называется форматированием строк, о нем мы поговорим в другой статье. Сейчас вам достаточно знать, что заменяется на firstNumber , следующей за строкой, а заменяется на secondNumber .

Арифметические операторы

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

int x = 5; int y = 10; int z = x + y; // z = 15

Название оператора

Читайте также:  Html borders without css

Пример 2. Используем арифметические операторы

using System; namespace Operator < class ArithmeticOperator < public static void Main(string[] args) < double firstNumber = 14.40, secondNumber = 4.60, result; int num1 = 26, num2 = 4, rem; // Оператор сложения result = firstNumber + secondNumber; Console.WriteLine("+ = ", firstNumber, secondNumber, result); // Оператор вычитания result = firstNumber - secondNumber; Console.WriteLine(" - = ", firstNumber, secondNumber, result) // Оператор умножения result = firstNumber * secondNumber; Console.WriteLine(" * = ", firstNumber, secondNumber, result); // Оператор деления result = firstNumber / secondNumber; Console.WriteLine(" / = ", firstNumber, secondNumber, result); // Оператор взятия остатка rem = num1 % num2; Console.WriteLine(" % = ", num1, num2, rem); > > >
14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2

Операторы сравнения

Операторы сравнения (они же — операторы отношения) используются для проверки связи между двумя операндами. Если сравнение истинно, результат будет true , иначе — false . Операторы отношения обычно используются в условиях и циклах.

Название оператора

Пример 3. Используем операторы сравнения

using System; namespace Operator < class RelationalOperator < public static void Main(string[] args) < bool result; int firstNumber = 10, secondNumber = 20; result = (firstNumber==secondNumber); Console.WriteLine("== возвращает ",firstNumber, secondNumber, result); result = (firstNumber > secondNumber); Console.WriteLine(" > возвращает ",firstNumber, secondNumber, result); result = (firstNumber < secondNumber); Console.WriteLine(" < возвращает ",firstNumber, secondNumber, result); result = (firstNumber >= secondNumber); Console.WriteLine(" >= возвращает ",firstNumber, secondNumber, result); result = (firstNumber <= secondNumber); Console.WriteLine(" <= возвращает ",firstNumber, secondNumber, result); result = (firstNumber != secondNumber); Console.WriteLine(" != возвращает ",firstNumber, secondNumber, result); > > > 
10 == 20 возвращает False
10 > 20 возвращает False
10 < 20 возвращает True
10 >= 20 возвращает False
10 10 != 20 возвращает True

Логические операторы

Логические операторы используются для выполнения таких логических операций, как AND (ИЛИ), OR (И) и т. д. Логические операторы работают с булевыми выражениями и возвращают булевые значения true и false . Логические операторы нужны для принятия решений и в циклах.

Источник

C# operators and expressions

C# provides a number of operators. Many of them are supported by the built-in types and allow you to perform basic operations with values of those types. Those operators include the following groups:

  • Arithmetic operators that perform arithmetic operations with numeric operands
  • Comparison operators that compare numeric operands
  • Boolean logical operators that perform logical operations with bool operands
  • Bitwise and shift operators that perform bitwise or shift operations with operands of the integral types
  • Equality operators that check if their operands are equal or not

Typically, you can overload those operators, that is, specify the operator behavior for the operands of a user-defined type.

The simplest C# expressions are literals (for example, integer and real numbers) and names of variables. You can combine them into complex expressions by using operators. Operator precedence and associativity determine the order in which the operations in an expression are performed. You can use parentheses to change the order of evaluation imposed by operator precedence and associativity.

In the following code, examples of expressions are at the right-hand side of assignments:

int a, b, c; a = 7; b = a; c = b++; b = a + b * c; c = a >= 100 ? b : c / 10; a = (int)Math.Sqrt(b * b + c * c); string s = "String literal"; char l = s[s.Length - 1]; var numbers = new List(new[] < 1, 2, 3 >); b = numbers.FindLast(n => n > 1); 

Typically, an expression produces a result and can be included in another expression. A void method call is an example of an expression that doesn’t produce a result. It can be used only as a statement, as the following example shows:

Console.WriteLine("Hello, world!"); 

Here are some other kinds of expressions that C# provides:

    Interpolated string expressions that provide convenient syntax to create formatted strings:

var r = 2.3; var message = $"The area of a circle with radius is ."; Console.WriteLine(message); // Output: // The area of a circle with radius 2.3 is 16.619. 
int[] numbers = < 2, 3, 4, 5 >; var maximumSquare = numbers.Max(x => x * x); Console.WriteLine(maximumSquare); // Output: // 25 
var scores = new[] < 90, 97, 78, 68, 85 >; IEnumerable highScoresQuery = from score in scores where score > 80 orderby score descending select score; Console.WriteLine(string.Join(" ", highScoresQuery)); // Output: // 97 90 85 

You can use an expression body definition to provide a concise definition for a method, constructor, property, indexer, or finalizer.

Operator precedence

In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence. In the following example, the multiplication is performed first because it has higher precedence than addition:

var a = 2 + 2 * 2; Console.WriteLine(a); // output: 6 

Use parentheses to change the order of evaluation imposed by operator precedence:

var a = (2 + 2) * 2; Console.WriteLine(a); // output: 8 

The following table lists the C# operators starting with the highest precedence to the lowest. The operators within each row have the same precedence.

Operators Category or name
x.y, f(x), a[i], x?.y , x?[y] , x++, x—, x!, new, typeof, checked, unchecked, default, nameof, delegate, sizeof, stackalloc, x->y Primary
+x, -x, !x, ~x, ++x, —x, ^x, (T)x, await, &x, *x, true and false Unary
x..y Range
switch, with switch and with expressions
x * y, x / y, x % y Multiplicative
x + y, x – y Additive
x > y, x >>> y Shift
x < y, x > y, x = y, is, as Relational and type-testing
x == y, x != y Equality
x & y Boolean logical AND or bitwise logical AND
x ^ y Boolean logical XOR or bitwise logical XOR
x | y Boolean logical OR or bitwise logical OR
x && y Conditional AND
x || y Conditional OR
x ?? y Null-coalescing operator
c ? t : f Conditional operator
x = y, x += y, x -= y, x *= y, x /= y, x %= y, x &= y, x |= y, x ^= y, x <>= y, x >>>= y, x ??= y, => Assignment and lambda declaration

Operator associativity

When operators have the same precedence, associativity of the operators determines the order in which the operations are performed:

  • Left-associative operators are evaluated in order from left to right. Except for the assignment operators and the null-coalescing operators, all binary operators are left-associative. For example, a + b — c is evaluated as (a + b) — c .
  • Right-associative operators are evaluated in order from right to left. The assignment operators, the null-coalescing operators, lambdas, and the conditional operator ?: are right-associative. For example, x = y = z is evaluated as x = (y = z) .

In an expression of the form P?.A0?.A1 , if P is null , neither A0 nor A1 are evaluated. Similarly, in an expression of the form P?.A0.A1 , because A0 isn’t evaluated when P is null, neither is A0.A1 . See the C# language specification for more details.

Use parentheses to change the order of evaluation imposed by operator associativity:

int a = 13 / 5 / 2; int b = 13 / (5 / 2); Console.WriteLine($"a = , b = "); // output: a = 1, b = 6 

Operand evaluation

Unrelated to operator precedence and associativity, operands in an expression are evaluated from left to right. The following examples demonstrate the order in which operators and operands are evaluated:

Expression Order of evaluation
a + b a, b, +
a + b * c a, b, c, *, +
a / b + c * d a, b, /, c, d, *, +
a / (b + c) * d a, b, c, +, /, d, *

Typically, all operator operands are evaluated. However, some operators evaluate operands conditionally. That is, the value of the leftmost operand of such an operator defines if (or which) other operands should be evaluated. These operators are the conditional logical AND ( && ) and OR ( || ) operators, the null-coalescing operators ?? and ??= , the null-conditional operators ?. and ?[] , and the conditional operator ?: . For more information, see the description of each operator.

C# language specification

For more information, see the following sections of the C# language specification:

See also

Источник

Инструкции (Руководство по программированию на C#)

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

Инструкция может состоять из одной строки кода, которая заканчивается точкой с запятой, или из ряда однострочных инструкций в блоке. Блок инструкций заключен в скобки <> и может содержать вложенные блоки. В следующем коде показаны два примера однострочных инструкций и блок многострочных инструкций:

 static void Main() < // Declaration statement. int counter; // Assignment statement. counter = 1; // Error! This is an expression, not an expression statement. // counter + 1; // Declaration statements with initializers are functionally // equivalent to declaration statement followed by assignment statement: int[] radii = < 15, 32, 108, 74, 9 >; // Declare and initialize an array. const double pi = 3.14159; // Declare and initialize constant. // foreach statement block that contains multiple statements. foreach (int radius in radii) < // Declaration statement with initializer. double circumference = pi * (2 * radius); // Expression statement (method invocation). A single-line // statement can span multiple text lines because line breaks // are treated as white space, which is ignored by the compiler. System.Console.WriteLine("Radius of circle #is . Circumference = ", counter, radius, circumference); // Expression statement (postfix increment). counter++; > // End of foreach statement block > // End of Main method body. > // End of SimpleStatements class. /* Output: Radius of circle #1 = 15. Circumference = 94.25 Radius of circle #2 = 32. Circumference = 201.06 Radius of circle #3 = 108. Circumference = 678.58 Radius of circle #4 = 74. Circumference = 464.96 Radius of circle #5 = 9. Circumference = 56.55 */ 

Типы инструкций

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

  • if
  • switch
  • do
  • for
  • foreach
  • while
  • break
  • continue
  • goto
  • return
  • yield
  • throw
  • try-catch
  • try-finally
  • try-catch-finally

Инструкции объявления

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

// Variable declaration statements. double area; double radius = 2; // Constant declaration statement. const double pi = 3.14159; 

Инструкции выражений

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

// Expression statement (assignment). area = 3.14 * (radius * radius); // Error. Not statement because no assignment: //circ * 2; // Expression statement (method invocation). System.Console.WriteLine(); // Expression statement (new object creation). System.Collections.Generic.List strings = new System.Collections.Generic.List(); 

Пустая инструкция

В следующих примерах показаны два способа использования пустой инструкции:

void ProcessMessages() < while (ProcessMessage()) ; // Statement needed here. >void F() < //. if (done) goto exit; //. exit: ; // Statement needed here. >

Внедренные инструкции

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

// Recommended style. Embedded statement in block. foreach (string s in System.IO.Directory.GetDirectories( System.Environment.CurrentDirectory)) < System.Console.WriteLine(s); >// Not recommended. foreach (string s in System.IO.Directory.GetDirectories( System.Environment.CurrentDirectory)) System.Console.WriteLine(s); 

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

if(pointB == true) //Error CS1023: int radius = 5; 

Чтобы устранить ошибку, поместите внедренную инструкцию в блок:

Вложенные блоки инструкций

Блоки инструкций могут быть вложенными, как показано в следующем коде:

foreach (string s in System.IO.Directory.GetDirectories( System.Environment.CurrentDirectory)) < if (s.StartsWith("CSharp")) < if (s.EndsWith("TempFolder")) < return s; >> > return "Not found."; 

Недостижимые инструкции

Если компилятор определяет, что поток управления ни при каких обстоятельствах не сможет достичь определенного оператора, то он выдаст предупреждение CS0162, как показано в следующем примере:

// An over-simplified example of unreachable code. const int val = 5; if (val < 4) < System.Console.WriteLine("I'll never write anything."); //CS0162 >

Спецификация языка C#

Дополнительные сведения см. в разделе Операторы в спецификации языка C#.

См. также

Источник

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