Métodos
## Objetivos de Aprendizaje
- Definir y llamar métodos
- Comprender parámetros y valores de retorno
- Dominar la sobrecarga de métodos
- Aprender parámetros out y ref
- Comprender parámetros opcionales
## Definir Métodos
### Estructura Básica
```csharp
static void Greet()
{
Console.WriteLine("¡Hola!");
}
```
### Método con Tipo de Retorno
```csharp
static int Add(int a, int b)
{
return a + b;
}
```
### Llamar Métodos
```csharp
class Program
{
static void Main()
{
Greet(); // método void
int sum = Add(5, 3); // devuelve 8
Console.WriteLine(sum);
}
static void Greet()
{
Console.WriteLine("¡Hola!");
}
static int Add(int a, int b)
{
return a + b;
}
}
```
## Parámetros y Argumentos
### Pasar Argumentos
```csharp
static void PrintName(string name)
{
Console.WriteLine("Nombre: " + name);
}
// Llamar con argumento
PrintName("Alice");
```
### Múltiples Parámetros
```csharp
static int CalculateArea(int width, int height)
{
return width * height;
}
int area = CalculateArea(5, 10); // 50
```
### Valores de Retorno
```csharp
static bool IsEven(int number)
{
return number % 2 == 0;
}
if (IsEven(4))
{
Console.WriteLine("Par");
}
```
## Tipos de Retorno
### void (Sin Retorno)
```csharp
static void PrintHello()
{
Console.WriteLine("Hola");
}
```
### Retorno Temprano
```csharp
static string GetGrade(int score)
{
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
```
### Múltiples Retornos (Cláusulas de Guardia)
```csharp
static bool Validate(int age, string name)
{
if (age < 0) return false;
if (string.IsNullOrEmpty(name)) return false;
// validación principal
return true;
}
```
## Sobrecarga de Métodos
### Mismo Nombre, Diferentes Parámetros
```csharp
static int Add(int a, int b)
{
return a + b;
}
static double Add(double a, double b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
```
### Cómo Funciona
```csharp
Add(5, 3); // Llama a Add(int, int)
Add(5.0, 3.0); // Llama a Add(double, double)
Add(1, 2, 3); // Llama a Add(int, int, int)
```
### Resolución de Sobrecarga
C# determina qué método llamar basándose en:
1. Número de argumentos
2. Tipo de argumentos
3. Orden de tipos de argumentos
## Parámetros Opcionales
### Valores por Defecto
```csharp
static void PrintMessage(string message, string prefix = "Info:")
{
Console.WriteLine($"{prefix} {message}");
}
PrintMessage("Hola"); // Info: Hola
PrintMessage("Hola", "Advertencia:"); // Advertencia: Hola
```
### Lo Opcional Debe Venir al Final
```csharp
// Válido
static void Example(int required, string optional = "default") { }
// Inválido
// static void Example(string optional = "default", int required) { }
```
## Argumentos Nominados
### Llamar por Nombre
```csharp
static void PrintOrder(string product, int quantity, double price)
{
Console.WriteLine($"{product}: {quantity} x {price}");
}
PrintOrder(product: "Widget", quantity: 5, price: 9.99);
PrintOrder(price: 9.99, product: "Widget", quantity: 5);
```
## Parámetro out
### Devolver Múltiples Valores
```csharp
static bool TryParse(string input, out int result)
{
try
{
result = int.Parse(input);
return true;
}
catch
{
result = 0;
return false;
}
}
// Uso
if (TryParse("123", out int number))
{
Console.WriteLine("Analizado: " + number);
}
```
### Descartar out (C# 7+)
```csharp
if (int.TryParse("123", out _))
{
Console.WriteLine("Número válido");
}
```
## Parámetro ref
### Pasar por Referencia
```csharp
static void DoubleIt(ref int x)
{
x = x * 2;
}
int num = 5;
DoubleIt(ref num);
Console.WriteLine(num); // 10
```
### ref vs out
| ref | out |
|-----|-----|
| Debe inicializarse antes de pasar | Debe asignarse dentro del método |
| Puede leer o escribir | Debe escribir antes de retornar |
## Parámetro params
### Argumentos Variables
```csharp
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
{
total += num;
}
return total;
}
// Puede pasar cualquier número de argumentos
Sum(1, 2, 3); // 6
Sum(1, 2, 3, 4, 5); // 15
Sum(); // 0
```
### Con Parámetros Regulares
```csharp
static void PrintAll(string prefix, params int[] numbers)
{
foreach (int num in numbers)
{
Console.WriteLine($"{prefix} {num}");
}
}
PrintAll("Valor:", 1, 2, 3);
```
## Métodos Estáticos vs de Instancia
### Métodos Estáticos
Pertenecen a la clase, no a la instancia:
```csharp
static class MathUtils
{
public static int Square(int x)
{
return x * x;
}
}
// Llamar sin crear instancia
int result = MathUtils.Square(5);
```
### Cuándo Usar static
- Métodos de utilidad (Math.Random(), Console.WriteLine())
- Métodos que no necesitan datos de instancia
- Constantes
### Métodos de Instancia
Requieren instancia de objeto:
```csharp
class Person
{
private string _name;
public void SetName(string name)
{
_name = name;
}
public string GetName()
{
return _name;
}
}
// Debe crear instancia
Person p = new Person();
p.SetName("Alice");
Console.WriteLine(p.GetName());
```
## Pasar Primitivos vs Referencias
### Primitivos (Pasar por Valor)
```csharp
static void DoubleIt(int x)
{
x = x * 2; // Solo afecta la copia local
}
int num = 5;
DoubleIt(num);
Console.WriteLine(num); // Sigue siendo 5
```
### Tipos de Referencia (Pasar por Referencia)
```csharp
static void ChangeName(Person p)
{
p.SetName("Bob"); // Afecta el objeto original
}
static void Reassign(Person p)
{
p = new Person(); // Solo afecta la copia local
p.SetName("Charlie");
}
Person person = new Person();
person.SetName("Alice");
ChangeName(person);
Console.WriteLine(person.GetName()); // Bob
```
## Recursión
### Método Llamándose a Sí Mismo
```csharp
static int Factorial(int n)
{
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
// factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
```
### Alternativa Iterativa
```csharp
static int Factorial(int n)
{
int result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
```
## Funciones Locales (C# 7+)
### Métodos Anidados
```csharp
static int Calculate(params int[] numbers)
{
int Sum()
{
int total = 0;
foreach (int n in numbers)
total += n;
return total;
}
int Count() => numbers.Length;
return Sum() / Count();
}
```
## Resumen
- Métodos: `modificador_acceso static? tipo_retorno nombre(params) { }`
- Sobrecarga: mismo nombre, diferentes parámetros
- Opcional: `tipo nombre = default` para parámetros opcionales
- Argumentos nominados: `method(param: value)`
- out: devuelve valor adicional (debe asignar dentro)
- ref: pasa por referencia (debe inicializar antes)
- params: `params tipo[]` para argumentos variables
- static: pertenece a la clase
- Recursión: método se llama a sí mismo (asegurar caso base)
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →