Zum Fußzeileninhalt springen
.NET HILFE

C# Nullable Typen (Wie es für Entwickler funktioniert)

When working with C#, you often need to handle null values, especially with reference types. Nullable types in C# provide a way to represent undefined or absent values for value types. This guide covers the essentials of C# nullable types, their practical uses, and how they work under different scenarios. We'll explore the IronPDF as well later in the article.

Nullable Types in C#

By default, value types in C# (e.g., int, bool, DateTime) cannot be assigned null values. To address this limitation, C# introduces nullable value types, allowing you to assign null to value types. Nullable types are particularly useful when you need to represent the absence of a valid value.

Declaring Nullable Types

To declare a nullable type in C#, you use the following syntax:

// Declare a nullable integer
int? nullableInt = null;
// Declare a nullable integer
int? nullableInt = null;
' Declare a nullable integer
Dim nullableInt? As Integer = Nothing
$vbLabelText   $csharpLabel

Here, int? is shorthand for Nullable<int>. The nullableInt variable can hold either an int value or null.

Checking for null

To check if a nullable type variable has a value or not, you can use the HasValue property or compare the variable directly with null, as shown below:

if (nullableInt.HasValue)
{
    // If nullableInt has a value, print it
    Console.WriteLine("Value: " + nullableInt.Value);
}
else
{
    // If nullableInt does not have a value, print a message
    Console.WriteLine("No value assigned.");
}
if (nullableInt.HasValue)
{
    // If nullableInt has a value, print it
    Console.WriteLine("Value: " + nullableInt.Value);
}
else
{
    // If nullableInt does not have a value, print a message
    Console.WriteLine("No value assigned.");
}
If nullableInt.HasValue Then
	' If nullableInt has a value, print it
	Console.WriteLine("Value: " & nullableInt.Value)
Else
	' If nullableInt does not have a value, print a message
	Console.WriteLine("No value assigned.")
End If
$vbLabelText   $csharpLabel

Alternatively, you can use the null coalescing operator (??) to provide a default value when the nullable type is null:

// Assign 0 if nullableInt is null
int result = nullableInt ?? 0;
Console.WriteLine("Result: " + result);
// Assign 0 if nullableInt is null
int result = nullableInt ?? 0;
Console.WriteLine("Result: " + result);
' Assign 0 if nullableInt is null
Dim result As Integer = If(nullableInt, 0)
Console.WriteLine("Result: " & result)
$vbLabelText   $csharpLabel

If nullableInt is null, result will be assigned the default value of 0.

Nullable Value Types vs Nullable Reference Types

In C#, value types (such as int, bool, and double) differ from reference types (like string, object). Nullable value types allow value types to represent null, while nullable reference types allow reference types to be non-nullable by default, thus reducing the risk of null reference exceptions.

Nullable Value Types

A nullable value type allows a value type to take a null value. To declare a nullable value type, append a question mark ? to the data type:

// Declare a nullable double
double? nullableDouble = null;
// Declare a nullable double
double? nullableDouble = null;
' Declare a nullable double
Dim nullableDouble? As Double = Nothing
$vbLabelText   $csharpLabel

In this example, nullableDouble can hold a double value or null.

Nullable Reference Types

Nullable reference types were introduced in C# 8.0. You can enable nullable reference types at the project level or by adding the #nullable enable directive at the beginning of your code file. With nullable reference types enabled, reference types must be explicitly marked as nullable using ?, helping to avoid potential runtime exceptions caused by null references.

#nullable enable
// Declare a nullable string
string? nullableString = null;
#nullable enable
// Declare a nullable string
string? nullableString = null;
'INSTANT VB TODO TASK: There is no equivalent to #nullable in VB:
'#nullable enable
' Declare a nullable string
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? nullableString = null;
Dim nullableString As String = Nothing
$vbLabelText   $csharpLabel

Here, nullableString is allowed to be null. If you declare a non-nullable reference type without the ?, the compiler will produce warnings if it detects potential null assignments.

Enabling Nullable Reference Types

To enable nullable reference types globally in a project, add the following line to your .csproj file:

<Nullable>enable</Nullable>
<Nullable>enable</Nullable>
XML

Once enabled, the compiler will treat reference types as non-nullable by default. This feature is especially handy to catch null reference issues at compile time rather than at runtime.

Practical Examples

Let’s explore some practical examples to solidify your understanding of nullable types.

Example 1: Nullable Type with Value Types

In this example, we’ll use a nullable type with int:

class Program
{
    static void Main(string[] args)
    {
        int? nullableInt = null;
        // Use null coalescing operator to assign a default value
        int b = nullableInt ?? 10;
        Console.WriteLine("b: " + b);
        if (nullableInt.HasValue)
        {
            // nullableInt has a value
            Console.WriteLine("nullableInt has value: " + nullableInt.Value);
        }
        else
        {
            // nullableInt is null
            Console.WriteLine("nullableInt is null");
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        int? nullableInt = null;
        // Use null coalescing operator to assign a default value
        int b = nullableInt ?? 10;
        Console.WriteLine("b: " + b);
        if (nullableInt.HasValue)
        {
            // nullableInt has a value
            Console.WriteLine("nullableInt has value: " + nullableInt.Value);
        }
        else
        {
            // nullableInt is null
            Console.WriteLine("nullableInt is null");
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim nullableInt? As Integer = Nothing
		' Use null coalescing operator to assign a default value
		Dim b As Integer = If(nullableInt, 10)
		Console.WriteLine("b: " & b)
		If nullableInt.HasValue Then
			' nullableInt has a value
			Console.WriteLine("nullableInt has value: " & nullableInt.Value)
		Else
			' nullableInt is null
			Console.WriteLine("nullableInt is null")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

Here, nullableInt is a nullable type variable of int. If nullableInt is null, b gets the value 10 due to the null coalescing operator. Otherwise, b takes the value of nullableInt.

Example 2: Nullable Reference Types

Now, let’s see how nullable reference types work:

#nullable enable
class Program
{
    static void Main()
    {
        string? nullableString = null;
        string nonNullableString = "Hello";
        // Use null coalescing operator to provide a default value for length
        Console.WriteLine(nullableString?.Length ?? 0);
        Console.WriteLine(nonNullableString.Length);
    }
}
#nullable enable
class Program
{
    static void Main()
    {
        string? nullableString = null;
        string nonNullableString = "Hello";
        // Use null coalescing operator to provide a default value for length
        Console.WriteLine(nullableString?.Length ?? 0);
        Console.WriteLine(nonNullableString.Length);
    }
}
'INSTANT VB TODO TASK: There is no equivalent to #nullable in VB:
'#nullable enable
Friend Class Program
	Shared Sub Main()
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? nullableString = null;
		Dim nullableString As String = Nothing
		Dim nonNullableString As String = "Hello"
		' Use null coalescing operator to provide a default value for length
		Console.WriteLine(If(nullableString?.Length, 0))
		Console.WriteLine(nonNullableString.Length)
	End Sub
End Class
$vbLabelText   $csharpLabel

In the code above, nullableString can be null, and the null coalescing operator ensures that if it is null, the length of the string defaults to 0.

Example 3: Nested Nullable Types

C# allows you to declare nested nullable types. For example:

// Redundant, but syntactically valid
int? nestedNullableInt = null;
// Redundant, but syntactically valid
int? nestedNullableInt = null;
' Redundant, but syntactically valid
Dim nestedNullableInt? As Integer = Nothing
$vbLabelText   $csharpLabel

While nested nullable types may seem redundant, they are syntactically valid in C#. However, in practice, nested nullable types don't provide any additional functionality and are rarely used.

Null Coalescing Operator (??)

The null coalescing operator (??) is frequently used with nullable types to provide a default value when the nullable type is null. This operator simplifies code by avoiding explicit if-else checks.

int? nullableValue = null;
// Assign -1 if nullableValue is null
int defaultValue = nullableValue ?? -1;
int? nullableValue = null;
// Assign -1 if nullableValue is null
int defaultValue = nullableValue ?? -1;
Dim nullableValue? As Integer = Nothing
' Assign -1 if nullableValue is null
Dim defaultValue As Integer = If(nullableValue, -1)
$vbLabelText   $csharpLabel

In this example, if nullableValue is null, defaultValue will be assigned -1. Otherwise, defaultValue will take the value of nullableValue.

Compile-Time Errors and Nullable Types

With nullable reference types enabled, C# produces warnings and errors during compilation when it detects potential issues with null assignments. These compile-time errors help catch issues early, making your code more robust.

Consider the following example:

string? nullableString = null;
// This will produce a compiler warning because nullableString may be null
string nonNullableString = nullableString;
string? nullableString = null;
// This will produce a compiler warning because nullableString may be null
string nonNullableString = nullableString;
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? nullableString = null;
Dim nullableString As String = Nothing
' This will produce a compiler warning because nullableString may be null
Dim nonNullableString As String = nullableString
$vbLabelText   $csharpLabel

In this case, assigning nullableString to nonNullableString produces a compiler warning because nullableString may be null, and assigning it to a non-nullable type could lead to runtime exceptions.

Using Nullable Types with IronPDF

C# Nullable Types (How It Works For Developers): Figure 1 - IronPDF: C# PDF Library

IronPDF is a C# PDF library designed to help developers create, edit, and manipulate PDF files directly from .NET applications. You can convert HTML to PDF, generate reports, or even handle complex document structures.

Nullable types are especially useful in dynamic report generation scenarios, such as when you're generating a PDF for an accountant with incomplete financial data. By using nullable types, you can manage optional fields, avoid exceptions, and provide default values.

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        int? optionalIncome = null;  // Nullable type for optional income
        string? clientName = "Iron Dev";  // Nullable reference type for client name
        var renderer = new ChromePdfRenderer();
        string htmlContent = $@"
            <h1>Financial Report</h1>
            <p>Client Name: {clientName ?? "Unknown"}</p>
            <p>Income: {optionalIncome?.ToString() ?? "Data not available"}</p>";
        // Render the HTML to a PDF
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to disk
        pdf.SaveAs("FinancialReport.pdf");
        Console.WriteLine("PDF Generated Successfully.");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        int? optionalIncome = null;  // Nullable type for optional income
        string? clientName = "Iron Dev";  // Nullable reference type for client name
        var renderer = new ChromePdfRenderer();
        string htmlContent = $@"
            <h1>Financial Report</h1>
            <p>Client Name: {clientName ?? "Unknown"}</p>
            <p>Income: {optionalIncome?.ToString() ?? "Data not available"}</p>";
        // Render the HTML to a PDF
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to disk
        pdf.SaveAs("FinancialReport.pdf");
        Console.WriteLine("PDF Generated Successfully.");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim optionalIncome? As Integer = Nothing ' Nullable type for optional income
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? clientName = "Iron Dev";
		Dim clientName As String = "Iron Dev" ' Nullable reference type for client name
		Dim renderer = New ChromePdfRenderer()
		Dim htmlContent As String = $"
            <h1>Financial Report</h1>
            <p>Client Name: {If(clientName, "Unknown")}</p>ignoreignore<p>Income: {If(optionalIncome?.ToString(), "Data not available")}</p>"
		' Render the HTML to a PDF
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF to disk
		pdf.SaveAs("FinancialReport.pdf")
		Console.WriteLine("PDF Generated Successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Nullable Types (How It Works For Developers): Figure 2 - Example code output

In this code, nullable types (int? and string?) are used to handle missing data safely. The null coalescing operator (??) ensures that if any data is missing, a default value is used in the PDF.

Conclusion

C# Nullable Types (How It Works For Developers): Figure 3 - IronPDF licensing page

Nullable types in C# are a powerful tool for handling null values in both value types and reference types. By using nullable types, you can avoid null reference exceptions and improve the robustness of your code. Remember to enable nullable reference types in new projects to benefit from compile-time error checking, and use the null coalescing operator (??) to simplify your code when dealing with nullable types.

IronPDF offers a free trial to help you explore its features before making a commitment. With no cost upfront, you can test the waters and see how it fits into your development process. Once you're ready to move forward, licenses start from $799.

Häufig gestellte Fragen

Wie können nullable Typen bei der dynamischen PDF-Erstellung genutzt werden?

Nullable Typen können bei der dynamischen PDF-Erstellung entscheidend sein, indem sie es ermöglichen, optionale Felder sicher darzustellen, unter Verwendung von Bibliotheken wie IronPDF. Dies stellt sicher, dass fehlende Daten angemessen behandelt werden, wobei erforderlichenfalls Standardwerte bereitgestellt werden.

Wie sieht die Syntax zur Deklaration von Nullable-Typen in C# aus?

In C# können Sie einen Nullable-Typ deklarieren, indem Sie ein Fragezeichen '?' an den Datentyp anhängen. Um beispielsweise einen Nullable-Integer zu deklarieren, würden Sie int? nullableInt = null; schreiben.

Können Nullable-Typen in C# die Robustheit von generierten Berichten beeinflussen?

Ja, die Verwendung von Nullable-Typen kann die Robustheit von generierten Berichten erhöhen, indem sichergestellt wird, dass optionale Felder keine Fehler verursachen, wenn ihre Werte fehlen. Bibliotheken wie IronPDF können Nullable-Typen nutzen, um diese Bedingungen effizient zu verwalten.

Wie helfen nullable Referenztypen, Laufzeitfehler zu verhindern?

Nullable Referenztypen, eingeführt in C# 8.0, helfen, Laufzeitfehler zu verhindern, indem Referenztypen standardmäßig nicht-nullable sind. Dies reduziert das Risiko von Nullverweis-Ausnahmen und ermöglicht eine frühzeitige Erkennung potenzieller Probleme während der Kompilierung.

Welche Rolle spielt der Null-Koaleszenz-Operator bei der Verwaltung von Nullable-Typen?

Der Null-Koaleszenz-Operator ?? wird zur Verwaltung von Nullable-Typen verwendet, indem er einen Standardwert bereitstellt, wenn ein Nullable-Typ null ist. Er vereinfacht den Code und hilft, explizite If-Else-Prüfungen zu vermeiden.

Wie kann geprüft werden, ob ein Nullable-Typ in C# einen Wert hat?

Sie können feststellen, ob ein Nullable-Typ in C# einen Wert hat, indem Sie die HasValue-Eigenschaft verwenden oder die Variable direkt mit null vergleichen.

Was sind einige typische Szenarien für die Verwendung von Nullable-Typen in C#-Anwendungen?

Nullable-Typen werden oft in Situationen verwendet, in denen Daten unvollständig oder optional sein können, wie beispielsweise bei Formulareingaben, Konfigurationseinstellungen oder beim Umgang mit Datenbanken, die Nullwerte erlauben. Sie sind besonders nützlich bei der dynamischen Berichtserstellung mit Bibliotheken wie IronPDF.

Wie beeinflusst das Aktivieren von Nullable-Referenztypen die C#-Projekterstellung?

Die Aktivierung von nullable Referenztypen in einem C#-Projekt führt zu Kompilierungswarnungen und -fehlern aufgrund potenzieller Nullreferenzprobleme, wodurch Probleme frühzeitig erkannt werden und die Entwicklung robusterer Codes gefördert wird.

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