Menu
CoddyTech

Analizar sin excepciones

Lección 6 de 48 del curso C# para desarrolladores de Ruby de Coddy.

Ruby ofrece dos formas habituales de convertir texto en un número: Integer() genera ArgumentError si el texto no tiene un formato válido, y to_i devuelve silenciosamente 0 o un prefijo inicial. En cambio, C# TryParse devuelve un bool y escribe el número mediante un parámetro out, rechazando el texto parcial y el desbordamiento de int. Una declaración de C# no analiza cadenas automáticamente.

TryParse devuelve un bool y escribe el valor convertido mediante un parámetro out. A diferencia de Parse, no genera excepciones ante texto con formato incorrecto o desbordamientos habituales. Usa una cultura explícita para un formato destinado a máquinas. Declarar un tipo por sí solo no convierte texto externo.

Referencia de Ruby

begin
  number = Integer("17")
  puts number
rescue ArgumentError
  puts "invalid"
end

Instrucciones de C# dentro de Main

int number;
bool ok = int.TryParse("17", out number);
Console.WriteLine(ok ? number.ToString() : "invalid");

Estos son fragmentos didácticos específicos. Los archivos del desafío incluyen envoltorios ejecutables completos; los fragmentos anteriores muestran las declaraciones y las instrucciones pertinentes.

Salida de referencia:

17

Salida de C#:

17
challenge icon

Desafío

Fácil

La entrada es una línea de texto. Analiza un entero con signo en base diez, con espacios opcionales alrededor. Si tiene éxito, devuelve el doble como texto; de lo contrario, devuelve invalid. Las entradas válidas están entre -1000000 y 1000000; el texto que representa un desbordamiento es invalid.

Edita los archivos C# desbloqueados. El archivo bloqueado visible Main.cs lee las líneas descritas, llama a Exercise.Solve, verifica que la entrada no se haya modificado e imprime el resultado con un único salto de línea final. Mantén las API declaradas. No agregues un segundo Main ni imprimas mensajes de diagnóstico.

Pruébalo tú mismo

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0]; string before0=Snapshot(a0);

var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de C# para desarrolladores de Ruby

Practica por tu cuenta: Compilador de C# online