E1 · Estudiante con notas, en C#
clase + List + propiedades · ★★Traduce la clase Estudiante de la semana 8: lista privada de notas, validación de 0 a 10, Promedio y Aprobado como propiedades calculadas, y ToString() (el __str__ de C#).
Solución
var e = new Estudiante("Carla", "2026-0412");
e.AgregarNota(7.5m);
e.AgregarNota(5.0m);
e.AgregarNota(8.0m);
Console.WriteLine(e);
try { e.AgregarNota(11m); }
catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"Error: {ex.ParamName} fuera de rango"); }
public class Estudiante
{
private readonly List<decimal> notas = new();
public string Nombre { get; }
public string Carnet { get; }
public Estudiante(string nombre, string carnet)
{
Nombre = nombre;
Carnet = carnet;
}
public void AgregarNota(decimal nota)
{
if (nota < 0 || nota > 10)
throw new ArgumentOutOfRangeException(nameof(nota));
notas.Add(nota);
}
public decimal Promedio => notas.Count == 0 ? 0 : Math.Round(notas.Sum() / notas.Count, 2);
public bool Aprobado => Promedio >= 6;
public override string ToString() =>
$"{Carnet} {Nombre}: {Promedio} ({(Aprobado ? "aprobado" : "en riesgo")})";
}
2026-0412 Carla: 6.83 (aprobado)
Error: nota fuera de rango
override string ToString() hace que Console.WriteLine(e) muestre el objeto en términos del negocio. notas.Sum() suma la lista.