C#

C# – Operators

Operators allow processing of primitive data types and objects. They take as an input one or more operands and return some value as a result. Operators in C# are special characters (such as “+”, “.”, “^”, etc.) and they perform transformations on one, two or three operands. Examples of operators in C# are the signs for adding, subtracting, multiplication and division from math (+, -, *, /) and the operations they perform on the integers and the real numbers.

Operators in C#

Operators in C# can be separated in several different categories:

  • Arithmetic operators – they are used to perform simple mathematical operations.
  • Assignment operators – allow assigning values to variables.
  • Comparison operators – allow comparison of two literals and/or variables.
  • Logical operators – operators that work with Boolean data types and Boolean expressions.
  • Bitwise operators – used to perform operations on the binary representation of numerical data.
  • Type conversion operators – allow conversion of data from one type to another.
Operators
int a = 7 + 9; 
Console.WriteLine(a); // 16 
string firstName = "John"; 
string lastName = "Doe"; 
// Do not forget the space between them 
string fullName = firstName + " " + lastName; 
Console.WriteLine(fullName); // John Doe 
Highest Priority
Lowest priority

Arithmetic Operators

The arithmetic operators perform arithmetic operations on all the numeric type operands such as sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal.

OperatorNameDescriptionExample
+AdditionComputes the sum of left and right operands.int x = 5 + 5;
SubtractionSubtract the right operand from the left operandint x = 5 – 1;
*MultiplicationMultiply left and right operandint x = 5 * 1;
/DivisionDivides the left operand by the right operandint x = 10 / 2;
%ReminderComputes the remainder after dividing its left operand by its right operandint x = 5 % 2;
++Unary incrementUnary increment ++ operator increases its operand by 1x++
Unary decrementUnary decrement — operator decreases its operand by 1x–
+Unary plusReturns the value of operand+5
Unary minusComputes the numeric negation of its operand.-5
 int squarePerimeter = 17;
 double squareSide = squarePerimeter / 4.0;
 double squareArea = squareSide * squareSide;
 Console.WriteLine(squareSide); // 4.25
 Console.WriteLine(squareArea); // 18.0625 
 
 int a = 5; int b = 4;
 Console.WriteLine(a + b);      // 9 
 Console.WriteLine(a + (b++));  // 9 
 Console.WriteLine(a + b);      // 10 
 Console.WriteLine(a + (++b));  // 11 
 Console.WriteLine(a + b);      // 11 
 Console.WriteLine(14 / a);     // 2 
 Console.WriteLine(14 % a);     // 4 
 
 int one = 1; int zero = 0;
 // Console.WriteLine(one / zero); // DivideByZeroException 
 
 double dMinusOne = -1.0; double dZero = 0.0;
 Console.WriteLine(dMinusOne / zero); // -Infinity
 Console.WriteLine(one / dZero); // Infinity

Logical Operators

Logical (Boolean) operators take Boolean values and return a Boolean result (true or false). The basic Boolean operators are “AND” (&&), “OR” (||), “exclusive OR” (^) and logical negation (!). The following table contains the logical operators in C# and the operations that they perform:

OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non zero then condition becomes true.(A && B) is false.
||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.
 bool a = true; bool b = false;
 Console.WriteLine(a && b);              // False 
 Console.WriteLine(a || b);              // True 
 Console.WriteLine(!b);                  // True 
 Console.WriteLine(b || true);           // True 
 Console.WriteLine((5 > 7) ^ (a == b));  // False 

Bitwise Operators

A bitwise operator is an operator that acts on the binary representation of numeric types. In computers all the data and particularly numerical data is represented as a series of ones and zeros. The binary numeral system is used for this purpose. For example, number 55 in the binary numeral system is represented as 00110111.

Bitwise

Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100 B = 0000 1101

A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

Bitwise
 byte a = 3;                 // 0000 0011 = 3 
 byte b = 5;                 // 0000 0101 = 5 
 
 Console.WriteLine(a | b);   // 0000 0111 = 7
 Console.WriteLine(a & b);   // 0000 0001 = 1
 Console.WriteLine(a ^ b);   // 0000 0110 = 6
 Console.WriteLine(~a & b);  // 0000 0100 = 4 
 Console.WriteLine(a << 1);  // 0000 0110 = 6 
 Console.WriteLine(a << 2);  // 0000 1100 = 12 
 Console.WriteLine(a >> 1);  // 0000 0001 = 1 

Comparison Operators

Comparison operators in C# are used to compare two or more operands. C# supports the following comparison operators:

  • greater than (>)
  • less than (<)
  • greater than or equal to (>=)
  • less than or equal to (<=)
  • equality (==) – difference (!=)

All comparison operators in C# are binary (take two operands) and the returned result is a Boolean value (true or false). Comparison operators have lower priority than arithmetical operators but higher than the assignment operators.

 int x = 10, y = 5;
 Console.WriteLine("x > y : " + (x > y));    // True
 Console.WriteLine("x < y : " + (x < y));    // False
 Console.WriteLine("x >= y : " + (x >= y));  // True
 Console.WriteLine("x <= y : " + (x <= y));  // False
 Console.WriteLine("x == y : " + (x == y));  // False 
 Console.WriteLine("x != y : " + (x != y));  // True 

Assignment Operators

The operator for assigning value to a variable is “=” (the character for mathematical equation). The syntax used for assigning value is as it follows:
operand1 = literal, expression or operand2;
Assignment Operators – Example
Here is an example to show the usage of the assignment operator:

int x = 6;
string helloString = "Hello string.";
int y = x;

In the example we assign value 6 to the variable x. On the second line we assign a text literal to the variable helloString, and on the third line we copy the value of the variable x to the variable y.

Conditional Operator

One of C#’s most fascinating operators is the ?, which is C#’s conditional operator. The ? operator is often used to replace certain types of if-then-else constructions. The ? is called a ternary operator because it requires three operands. It takes the general form

Exp1 ? Exp2 : Exp3;

where Exp1 is a bool expression, and Exp2 and Exp3 are expressions. The type of Exp2 and Exp3 must be the same (or, an implicit conversion between them must exist). Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated, and its value becomes the value of the expression.

Consider this example, which assigns absval the absolute value of val: absval = val < 0 ? -val : val; // get absolute value of val Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval will be assigned the negative of that value (which yields a positive value). Here is another example of the ? operator. This program divides two numbers, but will not allow a division by zero.

Type Conversion Operator

The operator for type conversion (type) is used to convert a variable from one type to another.
Operator “as”
The operator as also is used for type conversion but invalid conversion returns null, not an exception.
Operator “new”
The new operator is used to create and initialize new objects.
Operator “is”
The is operator is used to check whether an object is compatible with a given type (check object’s type).

using System;
class NoZeroDiv 
{  
static void Main() 
{    
int result; 
for(int i = -5; i < 6; i++)
{
     result = i != 0 ? 100 / i : 0; 
     if(i != 0) 
     Console.WriteLine("100 / " + i + " is " + result);
 }
} 
} 

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button