Zum Fußzeileninhalt springen
.NET HILFE

C# Null-Koaleszenz (Wie es für Entwickler funktioniert)

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.

Häufig gestellte Fragen

Wie verbessert der Null-Koaleszenz-Operator die Lesbarkeit von Code in C#?

Der Null-Koaleszenz-Operator `??` in C# verbessert die Lesbarkeit von Code, indem er null-Prüfungen vereinfacht und eine prägnante Möglichkeit bietet, Standardwerte zuzuweisen, wenn ein Nullable-Typ auftritt.

Was ist der Zweck des Null-Koaleszenz-Zuweisungsoperators in C#?

Der Null-Koaleszenz-Zuweisungsoperator `??=` weist den Wert seines rechten Operanden nur dann seinem linken Operanden zu, wenn der linke Operand null ist, was einen optimierten Code beim Arbeiten mit Nullable-Typen ermöglicht.

Können Sie ein Beispiel für die Verwendung des Null-Koaleszenz-Operators in einer C# PDF-Anwendung geben?

In einer C# PDF-Anwendung mit IronPDF könnten Sie den Null-Koaleszenz-Operator verwenden, um einen Standarddateinamen zuzuweisen, falls der Benutzer keinen angibt: string pdfName = userInputFileName ?? "default.pdf";.

Was sind einige häufige Fallstricke bei der Verwendung des Null-Koaleszenz-Operators?

Ein häufiger Fallstrick besteht darin, die Typkompatibilität zwischen den Operanden nicht sicherzustellen, was zu Typumwandlungsfehlern führen kann. Es ist wichtig, sicherzustellen, dass beide Operanden kompatible Typen sind, wenn der Null-Koaleszenz-Operator verwendet wird.

Wie steht der Null-Koaleszenz-Operator in Bezug zur Typkompatibilität in C#?

Der Null-Koaleszenz-Operator erfordert, dass beide Operanden kompatible Typen sind. Wenn dies nicht der Fall ist, wendet C# Typförderungsregeln an, um den Ergebnistyp zu bestimmen, was zu unerwartetem Verhalten führen kann, wenn nicht sorgfältig darauf geachtet wird.

Warum ist der Null-Koaleszenz-Operator vorteilhaft für Entwickler, die mit Nullable-Typen arbeiten?

Der Null-Koaleszenz-Operator ist vorteilhaft, weil er es Entwicklern ermöglicht, Nullable-Typen effizient zu handhaben, indem er Standardwerte bereitstellt und den Bedarf an ausführlichen bedingten Logiken reduziert.

Wie können Entwickler den Null-Koaleszenz-Operator verwenden, um null-Werte in C# Codebibliotheken zu verwalten?

Entwickler können den Null-Koaleszenz-Operator in C# Codebibliotheken verwenden, um Standardwerte zuzuweisen, wenn ein gegebener Wert null sein könnte, um so sicherzustellen, dass die Anwendung reibungslos ohne Nullverweis-Ausnahmen weiterläuft.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen