Menu
CoddyTech

Valores anulables y valores predeterminados

Lección 11 de 48 del curso C# para desarrolladores de C++ de Coddy.

C++ optional<int> es una analogía útil para C# int?, y value_or corresponde a ?? en este contrato. Ninguno debería tratar el cero como un valor ausente. La nulabilidad de las referencias en C# es un asunto aparte de los tipos de valor anulables en este compilador antiguo.

Int no puede contener null; int? es Nullable<int>. HasValue, Value y ?? hacen explícita la ausencia. El operador de fusión con null elige su alternativa solo cuando el valor es null. Esta es una sintaxis de tipo de valor anulable compatible con el compilador antiguo, no un análisis moderno de referencias anulables.

Referencia de C++

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
optional<int> count=0;
cout << count.value_or(9) << "\n";
}

Instrucciones de C# dentro de Main

int? count = 0;
Console.WriteLine(count ?? 9);

Estos son fragmentos didácticos centrados en el tema. Los archivos del desafío incluyen envoltorios ejecutables completos; los fragmentos anteriores muestran las declaraciones e instrucciones pertinentes.

Salida de referencia:

0

Salida de C#:

0
challenge icon

Desafío

Fácil

La primera línea es null o un entero; la segunda es el valor alternativo. Devuelve el valor de count a menos que sea null. Conserva los valores cero y negativos.

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 añadas 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] == "null" ? (int?)null : I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) 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 C++

Practica por tu cuenta: Compilador de C# online