Saltar al pie de página
.NET AYUDA

Coalescencia de nulos en C# (Cómo funciona para desarrolladores)

The null-coalescing operator ?? evaluates the right-hand operand and returns its result if the left-hand operand is a null reference; otherwise, it returns the value of its left-hand operand. If the left-hand operand evaluates to a non-nullable value type, the null-coalescing operator (??) does not evaluate its operand on the right-hand. The assignment operator ??= is a null-coalescing assignment that assigns the value of its right operand to its left operand only when the left operand evaluates to a nullable type value. If the operand on the left side evaluates to a non-null value, the null-coalescing assignment operator (??=) does not evaluate its right-hand operand. The null-coalescing operator is similar to the ternary operator.

In C#, the null-coalescing operator (??) is a binary operator. An operator that acts on two operands is referred to as a binary operator. When using the null-coalescing operator, two operands are required, and the operator evaluates each operand to determine the outcome. Now we are going to see null-coalescing and null-conditional operators usage in C# below.

How to use C# Null Coalescing Value Types

  1. Create a new C# project.
  2. Make sure the appropriate version is installed.
  3. Use the null-coalescing operator ??.
  4. Check the value or object reference types based on the requirement.
  5. Run the code.

Null Coalescing in C#

Null values in C# are handled by default provided by the null-coalescing operator (??), which is the idea of coalescing that is used to manage such values when dealing with nullable types or expressions that might result in null.

Syntax

The following is the syntax for the null-coalescing operator:

result = expression1 ?? expression2;
result = expression1 ?? expression2;
result = If(expression1, expression2)
$vbLabelText   $csharpLabel
  • expression1: A null value might be produced by this expression.
  • expression2: If expression1 is null, this is the default value or substitute expression to be used.
  • result: The variable holding the coalescing operation's outcome.

The null-coalescing operator offers a condensed method of assigning a default value when working with nullable types, which is its main goal in streamlining code and efficiently handling null data.

Benefits

  • Conciseness: Handles null checks without requiring complex conditional statements or ternary operators.
  • Code readability: Improved by explicitly stating that a default value would be provided if null is returned.

It's crucial to make sure the expression types being compared match or are compatible before using the null-coalescing operator.

Although useful, overusing the operator might make code harder to comprehend. Use it sparingly when it enhances code clarity.

When working with nullable types or scenarios requiring default values, the null-coalescing operator (??) in C# is an effective tool for managing null values and may help write more succinct and understandable code.

The null-coalescing operator ?? possesses the following type-related qualities:

Result Type Inference

The outcome type of the null-coalescing operator is the same as these operands if expressions 1 and 2 have the same type as shown in the following code.

int? Value = null;
int result = Value ?? 10;
int? Value = null;
int result = Value ?? 10;
Dim Value? As Integer = Nothing
Dim result As Integer = If(Value, 10)
$vbLabelText   $csharpLabel

Type Compatibility

The outcome type is the type to which both expressions can be implicitly converted if expressions 1 and 2 have distinct types but one can be implicitly converted to the other.

double? value = null;
int result = (int)(value ?? 5.5);
double? value = null;
int result = (int)(value ?? 5.5);
Imports System

Dim value? As Double = Nothing
Dim result As Integer = CInt(Math.Truncate(If(value, 5.5)))
$vbLabelText   $csharpLabel

Type Promotion

If the types of expressions 1 and 2 cannot be implicitly converted, the result type will be chosen following C#'s type promotion rules.

int? value = null;
long result = value ?? 100L;
int? value = null;
long result = value ?? 100L;
Dim value? As Integer = Nothing
Dim result As Long = If(value, 100L)
$vbLabelText   $csharpLabel

Consequently, the types of the operands involved and the C# type conversion rules dictate the type of variable or expression that holds the result of the null-coalescing operator (??). To guarantee the correct handling of types and values while employing the null-coalescing operator, it's crucial to take compatibility and probable type conversions into account.

Coalescing in IronPDF

Install IronPDF

To install the IronPDF library, enter the following code into the Package Manager:

Install-Package IronPdf

C# Null Coalescing (How It Works For Developers): Figure 1 - Install IronPDF

Alternatively, you may use the NuGet Package Manager to search for the package "IronPDF". You may choose and download the necessary package from this list of all the NuGet packages connected to IronPDF.

C# Null Coalescing (How It Works For Developers): Figure 2 - NuGet Package Manager

Create PDF with Null Coalescing

A C# library called IronPDF is used to create and work with PDF documents. The library offers features for working with PDFs, such as formatting, text processing, and image management. "Null-coalescing" is not a method or feature that is exclusive to IronPDF; rather, it is a language feature rather than a library-specific operation.

However, if you are working with IronPDF or any other library in your C# code, you may utilize the null-coalescing operators (??) that the C# language provides.

To handle null situations or provide default values, for example, while working with IronPDF objects, nullable value types or properties that may return null, you can use the null-coalescing operator.

The following example shows how the null-coalescing operator may be used with IronPDF:

using IronPdf;
using IronPdf.Pages;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int? x = null;

            // Use the null-coalescing operator to provide a default value if x is null
            var outputstr = $@"square of <b>{x}</b> is <b>{Math.Sqrt(x ?? 30)}</b>";

            // Render the HTML string as a PDF using IronPDF
            var pdfcreate = ChromePdfRenderer.StaticRenderHtmlAsPdf(outputstr);

            // Save the generated PDF to the file system
            pdfcreate.SaveAs("demo.pdf");

            // Wait for a key press to prevent the console from closing immediately
            Console.ReadKey();
        }
    }
}
using IronPdf;
using IronPdf.Pages;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int? x = null;

            // Use the null-coalescing operator to provide a default value if x is null
            var outputstr = $@"square of <b>{x}</b> is <b>{Math.Sqrt(x ?? 30)}</b>";

            // Render the HTML string as a PDF using IronPDF
            var pdfcreate = ChromePdfRenderer.StaticRenderHtmlAsPdf(outputstr);

            // Save the generated PDF to the file system
            pdfcreate.SaveAs("demo.pdf");

            // Wait for a key press to prevent the console from closing immediately
            Console.ReadKey();
        }
    }
}
Imports IronPdf
Imports IronPdf.Pages

Namespace ConsoleApp1
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim x? As Integer = Nothing

			' Use the null-coalescing operator to provide a default value if x is null
			Dim outputstr = $"square of <b>{x}</b> is <b>{Math.Sqrt(If(x, 30))}</b>"

			' Render the HTML string as a PDF using IronPDF
			Dim pdfcreate = ChromePdfRenderer.StaticRenderHtmlAsPdf(outputstr)

			' Save the generated PDF to the file system
			pdfcreate.SaveAs("demo.pdf")

			' Wait for a key press to prevent the console from closing immediately
			Console.ReadKey()
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Remember that IronPDF (or any library) does not provide a special feature or method for managing null values conditional operators; rather, the usage of the null-coalescing operator is based on general C# language features and concepts for handling a null conditional operator. To know more about the features and capabilities of IronPDF, visit the IronPDF Demos.

Output:

C# Null Coalescing (How It Works For Developers): Figure 3 - Preceding Example Output

Conclusion

In summary, C#'s null-coalescing operator (??) is a useful feature that makes handling null values in expressions and assignments easier and more efficient. This operator simplifies code by giving developers a clear way to handle scenarios in which a value could be null. This enables developers to specify default values or carry out alternative logic with ease. Its adaptability makes code more streamlined and effective, simplifying null tests and enhancing readability.

IronPDF offers a perpetual license, upgrade options, a year of software maintenance, and a thirty-day money-back guarantee, all included in the $799 Lite package. Users get thirty days to evaluate the product in real-world application settings during the watermarked trial period. Click the supplied IronPDF Licensing to learn more about IronPDF's cost, licensing, and trial version. To know more about Iron Software products, check the Iron Software website.

Preguntas Frecuentes

¿Cómo mejora el operador de coalición nula la legibilidad del código en C#?

El operador de coalición nula `??` en C# mejora la legibilidad del código al simplificar las verificaciones de nulos y proporcionar una forma concisa de asignar valores por defecto cuando se encuentra un tipo anulable.

¿Cuál es el propósito del operador de asignación de coalición nula en C#?

El operador de asignación de coalición nula `??=` asigna el valor de su operando derecho a su operando izquierdo solo si el operando izquierdo es nulo, permitiendo un código más sencillo al tratar con tipos anulables.

¿Puedes proporcionar un ejemplo de uso del operador de coalición nula en una aplicación PDF en C#?

En una aplicación PDF en C# usando IronPDF, podrías usar el operador de coalición nula para asignar un nombre de archivo por defecto si el usuario no lo especifica: string pdfName = userInputFileName ?? "default.pdf";.

¿Cuáles son algunas trampas comunes al usar el operador de coalición nula?

Una trampa común es no asegurar la compatibilidad de tipos entre operandos, lo que puede llevar a errores de conversión de tipos. Es crucial asegurar que ambos operandos sean de tipos compatibles al usar el operador de coalición nula.

¿Cómo se relaciona el operador de coalición nula con la compatibilidad de tipos en C#?

El operador de coalición nula requiere que ambos operandos sean de tipos compatibles. Si no lo son, C# aplica reglas de promoción de tipos para determinar el tipo de resultado, lo que puede llevar a un comportamiento inesperado si no se maneja cuidadosamente.

¿Por qué es beneficioso el operador de coalición nula para los desarrolladores que manejan tipos anulables?

El operador de coalición nula es beneficioso porque permite a los desarrolladores manejar de manera eficiente tipos anulables al proporcionar valores por defecto, reduciendo la necesidad de lógica condicional verbosa.

¿Cómo pueden los desarrolladores usar el operador de coalición nula para manejar valores nulos en bibliotecas de código C#?

Los desarrolladores pueden usar el operador de coalición nula en bibliotecas de código C# para asignar valores por defecto cuando un valor dado podría ser nulo, asegurando que la aplicación continúe funcionando sin excepciones de referencia nula.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más