THE OPERATORS

  • CAST AND OPERATORS IN C SHARP THE MATHEMATICAL OPERATORS

Suppose we have two variables x and y with the following values:

int x = 8 ;

int y = 4 ;

Operator

Description

Example

+

Sum or Concatenation

x + y = 12

Subtraction

x – y = 4

*

Multiplication

x * y = 32

/

Division

x / y = 2

%

Modulo (returns the remainder of an integer division)

x % y = 0

++

Increase

x++ = 9

Decrease

x– = 7

OPERAND OPERATOR OPERAND

      8                   +                  4

C sharpIn C#, an operator is a program element that is applied to one or more operands in an expression or statement. Operators that take an operand, such as the increment operator (++), are referred to as unary operators. Operators that take two operands, such as arithmetic operators (+, -, *, /), are referred to as binary operators. One operator, the conditional operator (?), takes three operands and is the only ternary operator in C#.

An expression is an operation evaluated at runtime, for example:

As regards the precedence between the operators, the same rules of arithmetic are followed, therefore in the previous case x is equal to 19. If you want, you can change the precedence between the operators using round brackets.

int x = ( 9 + 5) * 2 = 28

  • CAST AND OPERATORS IN C SHARP THE RELATION OR COMPARISON OPERATORS

They are used in C#, as well as in many other programming languages, to make comparisons between variables, in order to make decisions (and thus control the execution flow of the program).

Operator

Description

Example

==

Tests for equality

(x == y) // false

!=

Check for diversity

(x! = y) // true

>

Greater

(x> y) // true

<

Minor

(x< y) // false

>=

Greater than or equal

(x> = y) // true

<=

Less than or equal

(x< = y) // false

  • CAST AND OPERATORS IN C SHARP THE LOGICAL OPERATORS

There are three logical operators: AND, OR and NOT. They are used to create complex and complex conditions based on the occurrence (or non-occurrence) of a series of situations. We already know these operators and their truth tables when we talked about digital electronics.

Operator

Description

Example

&&

AND

(x> 9 && y< 5) // false.

||

OR

(x> 9 || y< 5) // true.

!

NOT

! (x> 9 && y< 5) // true

  • CAST AND OPERATORS IN CSHARP THE ASSIGNMENT OPERATORS

These operators are used to assign a value to a variable.

Operator

Description

Example

=

Assignment

x = 10 (assigns x the value 10)

+=

Assignment with addition

x += y is equivalent to x = x + y

-=

Assignment with subtraction

x -= y is equivalent to x = x – y

*=

Assignment with multiplication

x *= y is equivalent to x = x * y

/=

Assignment with division

x /= y is equivalent to x = x / y

Note that, as in other languages, C# uses different operators for assignment (=) and comparison (==).

EXAMPLE OF ASSIGNMENT WITH ADDITION

int a = 5 ;

a = a +3;

It is equivalent to:

a+=3;

C# provides us with a shorthand syntax for this type of operation. As for the increment ++ and decrement operators — there is a postfix notation and a prefix notation, both of which increase or decrease the variable or literal by one.

PREFIXED NOTATION

–a ++a

POSTFIXED NOTATION

a– a++

int a = 10 ;

int b = 5 + ++a; (prefix notation)

Console.Writeline (a); a=11

Console.Writeline (b); b=16

In this case ++a has precedence over the other operators, so first it is incremented and then 5 is added.

int a = 10

int b = 5 + a++ (postfix notation)

Console.Writeline (a); a=11

Console.Writeline (b); b=15

In this case a++ does not have precedence over the other operators, so first the sum between 10 and 5 is made, then a is increased.

CASTING

double d = 1200.5 ;

int a = 20 + d

If we ask the compiler to add an int and a double we get a compilation error because the destination int type that stores the value is narrower, less wide than a double. There are two types of casting, implicit casting which is performed by the compiler without our intervention and explicit casting in which we tell the compiler what we are doing. If you try to convert a narrower type (which therefore occupies fewer Bytes) into a wider one (which occupies more Bytes) the casting is implicit as there is no risk of loss of information. For example:

byte b = 10 ;

int a = 20 + b ;

However, if the destination type is an int which is narrower than a double, there is a risk of information loss. And this is why we are the ones who need to provide the compiler with an explicit cast since it assumes we know what we are doing.

double d = 1200.5;

int a = 20 + ( int )d

At this point the compiler compiles the Statement, but let’s see what the risks are linked to incorrect casting.

int a = 255 ;

byte b = ( byte )a ;

What happens if a takes on the value 256? It happens that a Byte is no longer sufficient to contain its value and there is an overflow or overflow error. Something happens internally in the representation of the bits and unexpected and absolutely incorrect values ​​end up in b.

THE CONVERT CLASS

int a = 300 ;

string s = Convert.ToString (a);

Console.WriteLine(s)

will print the string “300”

VISUAL STUDIO CODE FOR OPERATORS

using System;

namespace Operatori;

using System;

namespace Operatori;

internal class Program
{
    private static void Main(string[] args)
    {
        //ESEMPI OPERATORI BINARI (2 OPERANDI)
        var x = 45;
        var y = 10;
        var somma = x + y;
        var prodotto = x * y;
        var divisione = x / y;
        var modulo = (byte)(x % y); //CONVERSIONE ESPLICITA
        var division = (double)x / y;
        Console.WriteLine($"Divisione:{divisione},modulo:{modulo},Divisione floating point: {division}");
        //ESEMPI OPERATORI UNARI (1 OPERANDO)
        var x1 = 10;
        var y1 = -x1;
        y1 = y1 - 3;
        //E' EQUIVALENTE A 
        y1 -= 3;
        x1 = x1 + 1;
        //E' EQUIVALENTE A 
        x1 += 1;
        var a = 10;
        var b = 5 + ++a; /*Notazione prefissa ++a che incrementa di 1
        ha la precedenza su tutti gli altri operatori. Quindi prima
        viene incrementata a poi si somma 5*/
        var a1 = 10;
        var b1 = 5 + a1++; /*Notazione postfissa a++ che incrementa di 1
        non ha la precedenza su tutti gli altri operatori. Quindi prima
        viene eseguita la somma e al termine viene incrementata a*/
        Console.WriteLine($"x1:{x1},y1:{y1},a:{a},b:{b},a1:{a1},b1:{b1}");
        //ESEMPI OPERATORI LOGICI
        var z = 10;
        var k = 8;
        var v = z > 9 && k < 10;
        var s = z > 10 || k >= 8;
        var negazione = !(z > 9 && k < 10);
        Console.WriteLine($"v:{v},s:{s},negazione:{negazione}");
        //ESEMPI OPERATORI SUI BIT (Bitwise)
        var binary_shift = 0b10101011; //shiftato di 1 posizione a sinistra diventa 10101 0110  (342)
        //shiftato di una posizione a destra diventa 0101 0101 (85)   

        var binary1 = 0b1010;
        var binary2 = 0b1010;
        var binary3 = binary1 & binary2;
        var binary4 = 0b1111;
        var binary5 = 0b1010;
        var binary6 = binary4 | binary5;
        var binary7 = 0b1111;
        var binary8 = 0b1010;
        var binary9 = binary7 ^ binary8;
        var binary10 = binary_shift << 1;
        var binary11 = binary_shift >> 1;
        Console.WriteLine($"AND Binario: {binary3}, Or Binario: {binary6}, XOR {binary9}");
        Console.WriteLine($"Shift a sinistra di 1 posizione: {binary10}, shift a destra di 1 posizione {binary11}");
    }

VISUAL STUDIO CODE FOR CASTING

using System;
namespace Conversioni;
internal class Program
{
    private static void Main(string[] args)
    {
        //ESEMPI DI CAST IMPLICITO
        var a = 1200;
        var d = 1234.89 + a;
        byte b = 255;
        int c = b;
        //ESEMPI DI CAST IMPLICITO
        var f = 2345.89765f;
        var g = 100 + (int)f;
        long h = 123567789;
        var z = 5 + (int)h;
        //ESEMPIO DI OVERFLOW
        var x = 1235678654; //dovrebbe restituire 1.235.678.655
        var k = (short)(1 + x);
        Console.WriteLine("overflow {0}", k);
        //LA CLASSE CONVERT
        var m = 1200;
        var s = Convert.ToString(m);
        Console.WriteLine("Conversione di un intero in stringa {0}", s);
    }
}

IN-DEPTH ON OPERATORS

In C#, operators are special symbols that tell the compiler to perform specific mathematical or logical operations. Operators in C# can be classified into several categories, including arithmetic, logical, comparison, bitwise, and others. Here is a summary of the main operators in C#:

Arithmetic Operators

Used to perform mathematical operations.

+ : Addition

: Subtraction

* : Multiplication

/ : Division

% : Module (rest of the division)

++ : Increment (increase by 1)

: Decrement (decreases by 1)

Assignment Operators

Used to assign values ​​to variables.

= : Simple assignment

+= : Addition and assignment

-= : Subtraction and assignment

*= : Multiplication and assignment

/= : Division and assignment

%= : Module and assignment

Comparison Operators

Used to compare two values.

== : Equality

!= : Diversity

•> : Greater than

•< : Less than

•> = : Greater than or equal to

•< = : Less than or equal to

Logical Operators

Used for logical operations (usually with Boolean values).

&& : Logical AND

|| : Logical OR

! : Logical NOT

Bitwise Operators

Used for bit-level operations.

& : Bitwise AND

| : Bitwise OR

^ : Bitwise XOR (exclusive OR)

~ : NOT bitwise

•<< : Shift left

•>> : Shift right

Conditional Operators

?: : Ternary operator (conditional)

Type Operators

Used to verify or convert types.

is : Tests whether an object is of a certain type

as : Type conversion (returns null if conversion fails)

typeof : Gets the type of an object

sizeof : Gets the size of a type (for unmanaged types only)

checked : Check arithmetic overflow

unchecked : Disables arithmetic overflow checking

Operators Others

new : Create object instances

sizeof : Gets the size in bytes of a type

typeof : Gets the data type

Code Examples

int a = 5;
int b = 10;
int sum = a + b;  // Addizione
bool isEqual = (a == b);  // Confronto
bool logicalAnd = (a < b && b > 0);  // AND logico
int bitwiseAnd = a & b;  // AND bit a bit
int? result = a > b ? a : b;  // Operatore ternario

INSIGHT ON CASTING IN C#

Cast Operator in C#

The cast operator in C# is used to convert an object of one type to another type. This conversion can be implicit or explicit.

Implicit Conversion

Implicit conversion occurs automatically when there is no data loss. Common examples include converting from a smaller type to a larger type, such as from int to long .

Example:

int integer = 123;
long longnumber = integer ; // Implicit conversion

Explicit Conversion

Explicit conversion, however, must be specified using the cast () operator as it may result in data loss or runtime exception. It is often used when switching from a larger type to a smaller type.

Example:

double DecimalNumber = 123.45;
int integer = (int)decimalNumber ; // Explicit conversion

In this case, Integer will contain the value 123 , since the decimal part is truncated.

Casting objects and reference types

In addition to value types, casting is also used to convert between reference types. When working with inheritance, casting can convert a base type to a derived type and vice versa.

Example:

class Animal { }
class Dog : Animal { }

Animal myAnimal = new Dog();
Dog myDog = (Dog) myAnimal ; // Explicit cast

If the cast is invalid, an InvalidCastException will be raised. To avoid this, you can use the as operator or the is operator.

Example with as :

Dog myDog = myAnimale as Dog;
if ( myDog != null )
{
// Operations with myDog
}

In summary, the cast operator in C# is a powerful tool for type conversion, but it must be used carefully to avoid runtime errors or data loss.

LINKS TO PREVIOUS POSTS

THE C# LANGUAGE

FURTHER INFORMATION