Operadores
## Objetivos de Aprendizaje
- Dominar operadores aritméticos
- Comprender operadores de comparación
- Aprender operadores lógicos
- Trabajar con operadores de coalescencia nula
## Operadores Aritméticos
### Operaciones Básicas
```csharp
int a = 10, b = 3;
Console.WriteLine(a + b); // 13 (suma)
Console.WriteLine(a - b); // 7 (resta)
Console.WriteLine(a * b); // 30 (multiplicación)
Console.WriteLine(a / b); // 3 (división entera)
Console.WriteLine(a % b); // 1 (módulo/resto)
```
### Comportamiento de la División
```csharp
// La división entera trunca
Console.WriteLine(10 / 3); // 3, no 3.333
// Para punto flotante
Console.WriteLine(10.0 / 3.0); // 3.333...
```
### Incremento/Decremento
```csharp
int x = 5;
// Pre-incremento/decremento
Console.WriteLine(++x); // 6 (incrementa primero)
Console.WriteLine(--x); // 5 (decrementa primero)
// Post-incremento/decremento
Console.WriteLine(x++); // 5 (usa el valor, luego incrementa)
Console.WriteLine(x); // 6 (ahora incrementado)
int y = 5;
Console.WriteLine(y--); // 5 (usa el valor, luego decrementa)
Console.WriteLine(y); // 4
```
## Operadores de Comparación
### Operadores Relacionales
```csharp
int a = 5, b = 10;
Console.WriteLine(a == b); // False (igual)
Console.WriteLine(a != b); // True (no igual)
Console.WriteLine(a < b); // True (menor que)
Console.WriteLine(a > b); // False (mayor que)
Console.WriteLine(a <= b); // True (menor o igual)
Console.WriteLine(a >= b); // False (mayor o igual)
```
### No Confundir
```csharp
// = es asignación
// == es comparación
int x = 5;
// if (x = 10) // ¡Error! La asignación devuelve 10 ( truthy-ish)
// if (x == 5) // ¡Correcto! Esto compara
```
## Operadores Lógicos
### AND, OR, NOT
```csharp
bool a = true, b = false;
Console.WriteLine(a && b); // False (AND - ambos deben ser true)
Console.WriteLine(a || b); // True (OR - uno debe ser true)
Console.WriteLine(!a); // False (NOT - invierte)
```
### Evaluación de Cortocircuito
```csharp
// && se detiene si el primero es false
if (x != 0 && y / x > 2) // Seguro - no dividirá por cero
// || se detiene si el primero es true
if (obj == null || obj.IsValid()) // Seguro - no llamará en null
```
### Tabla de Verdad
| A | B | A && B | A \|\| B | !A |
|---|---|--------|----------|-----|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
## Operadores de Asignación
### Asignación Simple
```csharp
int x = 10;
```
### Asignación Compuesta
```csharp
int x = 10;
x += 5; // x = 15 (x = x + 5)
x -= 3; // x = 12 (x = x - 3)
x *= 2; // x = 24 (x = x * 2)
x /= 4; // x = 6 (x = x / 4)
x %= 5; // x = 1 (x = x % 5)
```
## Operadores de Coalcencia Nula
### ?? (Coalcencia Nula)
```csharp
string name = null;
string displayName = name ?? "Unknown";
// Equivalente a:
string displayName2 = (name != null) ? name : "Unknown";
```
### ??= (Asignación con Coalcencia Nula)
```csharp
string name = null;
name ??= "Unknown"; // Asigna solo si es null
// Ahora name es "Unknown"
```
### ?. (Condicional Nulo)
```csharp
string name = null;
int? length = name?.Length; // Devuelve null en lugar de lanzar excepción
// Navegación segura con verificación de null
if (name?.Length > 0)
{
Console.WriteLine(name);
}
```
## Operador Ternario
### Sintaxis
```csharp
// condición ? valorSiTrue : valorSiFalse
int max = (a > b) ? a : b;
string status = (age >= 18) ? "adult" : "minor";
```
## Operadores Bit a Bit
### Operaciones Binarias
```csharp
int a = 5, b = 3; // 101 y 011 en binario
Console.WriteLine(a & b); // 1 (AND: 101 & 011 = 001)
Console.WriteLine(a | b); // 7 (OR: 101 | 011 = 111)
Console.WriteLine(a ^ b); // 6 (XOR: 101 ^ 011 = 110)
Console.WriteLine(~a); // -6 (NOT: ~101 = ...010 = -6)
Console.WriteLine(a << 1); // 10 (desplazamiento izquierda: 101 << = 1010)
Console.WriteLine(a >> 1); // 2 (desplazamiento derecha: 101 >> = 10)
```
### Usos Comunes
```csharp
// Verificar si un bit está establecido
int flags = 0b1010; // 10 en decimal
if ((flags & 0b1000) != 0)
{
Console.WriteLine("El bit 3 está establecido");
}
// Establecer un bit
flags = flags | 0b0001;
// Cambiar un bit
flags = flags ^ 0b0100;
```
## Precedencia de Operadores
### De Mayor a Menor
| Prioridad | Operadores |
|-----------|-------------------|
| 1 | `()` |
| 2 | `++`, `--`, `!` |
| 3 | `*`, `/`, `%` |
| 4 | `+`, `-` |
| 5 | `<`, `>`, `<=`, `>=` |
| 6 | `==`, `!=` |
| 7 | `&`, `^`, `\|` (bit a bit) |
| 8 | `&&` |
| 9 | `\|\|` |
| 10 | `??`, `??=` |
| 11 | `?:` |
| 12 | `=`, `+=`, `-=`, etc. |
### Usar Paréntesis
```csharp
// Precedencia clara
if ((a > b) && (c < d))
{
}
// En lugar de confiar en la memoria
if (a > b && c < d) // Igual, pero menos claro
```
## Resumen
- Aritméticos: `+`, `-`, `*`, `/`, `%`
- Incremento/Decremento: `++x`, `x++`, `--x`, `x--`
- Comparación: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Lógicos: `&&`, `||`, `!`
- Asignación: `=`, `+=`, `-=`, etc.
- Coalcencia nula: `??`, `??=`, `?.`
- Bit a bit: `&`, `|`, `^`, `~`, `<<`, `>>`
- Ternario: `condición ? true : false`
- Usa paréntesis para aclarar precedencia
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →