Zum Fußzeileninhalt springen
.NET HILFE

C# init Schlüsselwort (Wie es für Entwickler funktioniert)

The init keyword in C# 9.0 introduced a new way of defining class properties for creating immutable objects. In earlier versions of C#, properties were typically used with get and set accessors to read from and write to object fields. However, with init, you can make writable properties only during object initialization, making them read-only afterward.

This tutorial will explore using the C# init keyword with practical examples and scenarios using the IronPDF library. You'll also learn about the critical differences between traditional property setters (set) and the new init-only setters.

Basic Example of the Init Keyword

Let's start with a basic example:

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

var person = new Person
{
    FirstName = "Iron",
    LastName = "Dev"
};

// person.FirstName = "Jane";  // This will give a compile-time error.
public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

var person = new Person
{
    FirstName = "Iron",
    LastName = "Dev"
};

// person.FirstName = "Jane";  // This will give a compile-time error.
Public Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
End Class

Private person = New Person With {
	.FirstName = "Iron",
	.LastName = "Dev"
}

' person.FirstName = "Jane";  // This will give a compile-time error.
$vbLabelText   $csharpLabel

C# Init Keyword (How It Works For Developers): Figure 1 - IDE throwing an error due to properties being marked as init-only

In this example, FirstName and LastName are marked as init-only properties. This means they can be assigned only during object initialization. After the object is created, attempting to change the values will cause a compile-time error.

Why Use the Init Keyword?

The main reason for using the init keyword is to make object properties immutable after initialization. Traditionally, you could mark properties as read-only to achieve immutability. However, you would often need a constructor that accepts all necessary values to set the fields, which can lead to constructor boilerplate code. With init, you can achieve the same goal using object initializers without writing long constructors.

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    // Without using constructor boilerplate for property initialization
}

var person = new Person
{
    FirstName = "John",
    LastName = "Doe"
};
public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    // Without using constructor boilerplate for property initialization
}

var person = new Person
{
    FirstName = "John",
    LastName = "Doe"
};
Public Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	' Without using constructor boilerplate for property initialization
End Class

Private person = New Person With {
	.FirstName = "John",
	.LastName = "Doe"
}
$vbLabelText   $csharpLabel

Object Initialization with Init-Only Properties

Using init works seamlessly with object initializers. Instead of relying on constructors to set values, you can define the properties you need directly while creating an object.

public class Point
{
    public int X { get; init; }
    public int Y { get; init; }
}

var point = new Point { X = 10, Y = 20 };

// point.X = 30;  // This will throw a compile-time error
public class Point
{
    public int X { get; init; }
    public int Y { get; init; }
}

var point = new Point { X = 10, Y = 20 };

// point.X = 30;  // This will throw a compile-time error
Public Class Point
	Public Property X() As Integer
	Public Property Y() As Integer
End Class

Private point = New Point With {
	.X = 10,
	.Y = 20
}

' point.X = 30;  // This will throw a compile-time error
$vbLabelText   $csharpLabel

This creates a simple, immutable object of type Point. Notice that the values for X and Y are set at initialization and can't be modified later.

Mixing init with Constructors

Although the primary use case for init is object initialization via object initializers, you can still use a constructor if needed. This is particularly useful when enforcing specific property values during object creation.

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}
public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}
Public Class Person
	Public Property FirstName() As String
	Public Property LastName() As String

	Public Sub New(ByVal firstName As String, ByVal lastName As String)
		Me.FirstName = firstName
		Me.LastName = lastName
	End Sub
End Class
$vbLabelText   $csharpLabel

You can use both constructors and init properties together. This approach offers more flexibility while still enforcing immutability after object construction.

Benefits of Init Over Private Set

Previously, developers used a private set accessor to limit property modification outside the class.

public class Person
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}
public class Person
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}
Public Class Person
	Private privateFirstName As String
	Public Property FirstName() As String
		Get
			Return privateFirstName
		End Get
		Private Set(ByVal value As String)
			privateFirstName = value
		End Set
	End Property
	Private privateLastName As String
	Public Property LastName() As String
		Get
			Return privateLastName
		End Get
		Private Set(ByVal value As String)
			privateLastName = value
		End Set
	End Property

	Public Sub New(ByVal firstName As String, ByVal lastName As String)
		Me.FirstName = firstName
		Me.LastName = lastName
	End Sub
End Class
$vbLabelText   $csharpLabel

Although this approach works, it requires constructor boilerplate code to initialize properties. Also, it allows the class itself to modify the properties later, which isn't always ideal for immutable objects. The init keyword removes this issue, as it only allows initialization at object creation time and blocks any modification afterward.

Handling Initialization with Read-Only Fields and Init Accessors

The init keyword can initialize fields or properties during object creation while they remain immutable afterward. While read-only fields provide immutability, the init accessor offers a similar capability for properties. Here's how you can handle immutability in two ways: using read-only fields and init properties.

Using Read-Only Fields with a Constructor

In this example, we use read-only fields for firstName and lastName, which are set during object construction. These fields can only be assigned once in the constructor and cannot be modified afterward:

public class Person
{
    private readonly string firstName;
    private readonly string lastName;

    public string FirstName => firstName;
    public string LastName => lastName;

    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
public class Person
{
    private readonly string firstName;
    private readonly string lastName;

    public string FirstName => firstName;
    public string LastName => lastName;

    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
Public Class Person
'INSTANT VB NOTE: The field firstName was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private ReadOnly firstName_Conflict As String
'INSTANT VB NOTE: The field lastName was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private ReadOnly lastName_Conflict As String

	Public ReadOnly Property FirstName() As String
		Get
			Return firstName_Conflict
		End Get
	End Property
	Public ReadOnly Property LastName() As String
		Get
			Return lastName_Conflict
		End Get
	End Property

	Public Sub New(ByVal firstName As String, ByVal lastName As String)
		Me.firstName_Conflict = firstName
		Me.lastName_Conflict = lastName
	End Sub
End Class
$vbLabelText   $csharpLabel

Using Init Accessors for Initialization

Alternatively, we can use the init accessor to create read-only properties that can be initialized during object creation but can't be changed afterward. This eliminates the need for read-only fields and provides a more modern syntax:

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}
public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}
Public Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
End Class
$vbLabelText   $csharpLabel

Introduction to IronPDF

C# Init Keyword (How It Works For Developers): Figure 2 - IronPDF: The C# PDF Library

IronPDF is a powerful PDF generation and manipulation library designed for C# developers. It simplifies working with PDFs by converting HTML, CSS, images, and other content into PDF documents. With features like pixel-perfect rendering, cross-platform support, and easy integration into .NET projects, IronPDF is ideal for developers needing to create high-quality PDFs quickly. You can use it with .NET Core, Framework, and Standard, and it supports a wide range of platforms, including Windows, Linux, and macOS.

Case: Using IronPDF with C# Init Keyword

To create immutable objects in a C# project while generating PDFs, you can combine the init keyword with IronPDF. The init keyword ensures the object's integrity after it's initialized, while IronPDF processes the data and generates PDFs based on that immutable model.

Make sure IronPDF is correctly referenced in your project. You can install it via NuGet:

Install-Package IronPdf

Here is the code example:

using IronPdf;

public class Person
{
    public int Id { get; init; }
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

public class PDFGenerator
{
    public static void CreatePersonPDF(Person person)
    {
        var htmlContent = $@"
        <html>
        <body>
            <h1>Person Information</h1>
            <p>ID: {person.Id}</p>
            <p>First Name: {person.FirstName}</p>
            <p>Last Name: {person.LastName}</p>
        </body>
        </html>";

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs($"Person_{person.Id}.pdf");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var person = new Person
        {
            Id = 1,
            FirstName = "Iron",
            LastName = "Dev"
        };

        PDFGenerator.CreatePersonPDF(person);
    }
}
using IronPdf;

public class Person
{
    public int Id { get; init; }
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

public class PDFGenerator
{
    public static void CreatePersonPDF(Person person)
    {
        var htmlContent = $@"
        <html>
        <body>
            <h1>Person Information</h1>
            <p>ID: {person.Id}</p>
            <p>First Name: {person.FirstName}</p>
            <p>Last Name: {person.LastName}</p>
        </body>
        </html>";

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs($"Person_{person.Id}.pdf");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var person = new Person
        {
            Id = 1,
            FirstName = "Iron",
            LastName = "Dev"
        };

        PDFGenerator.CreatePersonPDF(person);
    }
}
Imports IronPdf

Public Class Person
	Public Property Id() As Integer
	Public Property FirstName() As String
	Public Property LastName() As String
End Class

Public Class PDFGenerator
	Public Shared Sub CreatePersonPDF(ByVal person As Person)
		Dim htmlContent = $"
        <html>
        <body>
            <h1>Person Information</h1>
            <p>ID: {person.Id}</p>
            <p>First Name: {person.FirstName}</p>
            <p>Last Name: {person.LastName}</p>
        </body>
        </html>"

		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		pdf.SaveAs($"Person_{person.Id}.pdf")
	End Sub
End Class

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim person As New Person With {
			.Id = 1,
			.FirstName = "Iron",
			.LastName = "Dev"
		}

		PDFGenerator.CreatePersonPDF(person)
	End Sub
End Class
$vbLabelText   $csharpLabel

Conclusion

C# Init Keyword (How It Works For Developers): Figure 3 - IronPDF Licensing Page

In summary, the C# init keyword allows you to create immutable objects while offering flexibility during object initialization. It's a cleaner and safer alternative to private set accessors, reducing the need for constructor boilerplate code. Combining the init keyword with read-only fields, structs, and validation logic helps you build robust and secure data structures that preserve immutability without sacrificing readability or flexibility. IronPDF offers a free trial, and licenses start from $799. This gives you access to its full features, including editing, compressing, and securing PDFs.

Häufig gestellte Fragen

Wie kann ich HTML in PDF in C# konvertieren?

Sie können die RenderHtmlAsPdf-Methode von IronPDF verwenden, um HTML-Strings in PDFs zu konvertieren. Sie können auch HTML-Dateien mit RenderHtmlFileAsPdf in PDFs konvertieren.

Was ist der Zweck des init-Schlüsselworts in C#?

Das init-Schlüsselwort ermöglicht es, Eigenschaften zu definieren, die nur während der Objektinitialisierung gesetzt werden können, was danach die Unveränderlichkeit gewährleistet. Diese Funktion ist besonders nützlich für die Erstellung von Objekten, die sich nicht mehr ändern sollen, sobald sie erstellt wurden.

Wie verbessert das init-Schlüsselwort die Unveränderlichkeit von Objekten in C#?

Das init-Schlüsselwort ermöglicht es, Eigenschaften nur während der Initialisierungsphase des Objekts festzulegen, was Änderungen danach verhindert. Dies garantiert, dass Objekte nach ihrer Erstellung unveränderlich bleiben.

Können init-Eigenschaften mit Bibliotheken zur PDF-Erstellung verwendet werden?

Ja, init-Eigenschaften können mit Bibliotheken wie IronPDF verwendet werden, um PDFs aus unveränderlichen Objekten zu generieren, wodurch sichergestellt wird, dass die für das PDF verwendeten Daten während des gesamten Prozesses konsistent bleiben.

Welche Vorteile bietet die Verwendung des init-Schlüsselworts gegenüber traditionellen Setzmethoden?

Der Einsatz des init-Schlüsselworts gegenüber traditionellen Setzmethoden fördert die Unveränderlichkeit, reduziert den Bedarf an umfangreichem Konstruktorkode und stellt sicher, dass Objekteigenschaften nach der Initialisierung nicht mehr geändert werden können.

Wie kann ich die PDF-Erstellung mit unveränderlichen Eigenschaften in C# integrieren?

Sie können unveränderliche Objekte mit init-Eigenschaften erstellen und diese Objekte an IronPDF übergeben, das die Daten nutzen kann, um konsistente und zuverlässige PDF-Dokumente zu erzeugen.

Welche Rolle spielt das init-Schlüsselwort bei der Erstellung moderner C#-Anwendungen?

Das init-Schlüsselwort spielt eine entscheidende Rolle bei der Erstellung moderner C#-Anwendungen, indem es Entwicklern ermöglicht, unveränderliche Objekte mit prägnanter Syntax zu definieren, was die Code-Sicherheit erhöht und Fehler reduziert.

Wie kann ich eine Bibliothek zur PDF-Erstellung in einem C#-Projekt installieren?

Sie können eine Bibliothek wie IronPDF in Ihrem C#-Projekt installieren, indem Sie den NuGet-Paketmanager mit dem Befehl verwenden: Install-Package IronPdf.

Warum ist Unveränderlichkeit in der Anwendungsentwicklung wichtig?

Unveränderlichkeit ist wichtig, weil sie die Datenintegrität und Konsistenz innerhalb Ihrer Anwendung gewährleistet, was die Wartung erleichtert und die Wahrscheinlichkeit von Fehlern reduziert.

Welche praktischen Beispiele veranschaulichen die Verwendung des init-Schlüsselworts?

Ein praktisches Beispiel ist die Verwendung des init-Schlüsselworts, um eine Klasse mit Eigenschaften zu definieren, die nur während der Initialisierung gesetzt werden können, wodurch sichergestellt wird, dass das erstellte Objekt unverändert bleibt. Dies ist insbesondere in Szenarien nützlich, in denen Datenkonsistenz von entscheidender Bedeutung ist.

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