typestar

Nothing y Nullable en Visual Basic

Chequeos de Nothing, encadenamientos ?. e If() — el kit anti-nulos de VB.

Dim nickname As String = Nothing
Console.WriteLine(nickname Is Nothing)
Console.WriteLine($"length: {nickname?.Length}")

Dim fallback = If(nickname, "anonymous")
Console.WriteLine(fallback)

Dim price As Integer? = Nothing
If Not price.HasValue Then price = 25
Console.WriteLine(price.Value)

Dim discount As Integer? = Nothing
Console.WriteLine($"you save {If(discount, 0)}")

Cómo funciona

  1. Is Nothing prueba identidad contra la referencia nula.
  2. ?. llama solo cuando el receptor existe; si no, produce Nothing.
  3. If(a, b) de dos argumentos fusiona: gana el primer valor que no es Nothing.
  4. Integer? guarda un número o Nothing, con HasValue y Value.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
13
Caracteres a escribir
377
Tokens
80
Ritmo de tres estrellas
80 tpm

Al ritmo de tres estrellas de 80 tokens por minuto, este intento toma unos 60 segundos.

Escribe este fragmento

Paso 2 de 3 en Modismos de VB; paso 23 de 29 en Fundamentos del lenguaje.

← Anterior Siguiente →