Zum Fußzeileninhalt springen
.NET HILFE

C# Enums (Funktionsweise für Entwickler)

Body Content: Enums, which are short for enumerations, serve as a powerful feature that enables developers to establish a set of named constants. These constants make code more readable and maintainable by providing meaningful names for values. In this article, we will explore the basics and advanced concepts of enums in C# through various examples and explanations. Our goal is to provide a comprehensive understanding of enums and how they can be effectively used in your C# applications using the IronPDF library for PDF generation in .NET.

Introduction to Enum in C#

An enum is a value type in C# that enables a variable to be a set of predefined constants, each referred to as an enum member. The enum keyword is used to declare an enumeration type, providing a way to group constant values under a single name. Enums improve code readability and reduce errors caused by passing incorrect values.

// Define an enum with four members
enum Season { Spring, Summer, Autumn, Winter }
// Define an enum with four members
enum Season { Spring, Summer, Autumn, Winter }
' Define an enum with four members
Friend Enum Season
	Spring
	Summer
	Autumn
	Winter
End Enum
$vbLabelText   $csharpLabel

In the above code, Season is an enum type with four members: Spring, Summer, Autumn, and Winter. By defining this enum, we can now create variables of type Season that can only hold one of these four values.

Underlying Type of Enums

Understanding the Integer Value of Enum Members

By default, the underlying type of an enum in C# is int, known as the underlying integral type, and the integer values of enum members start from 0. Each member's integer value is incremented by 1 from the previous member unless explicitly specified. You can also define the underlying type of an enum to be any other integral type.

// Define an enum with a byte underlying type and specific values
enum Season : byte { Spring = 1, Summer, Autumn = 4, Winter }
// Define an enum with a byte underlying type and specific values
enum Season : byte { Spring = 1, Summer, Autumn = 4, Winter }
' Define an enum with a byte underlying type and specific values
Friend Enum Season As Byte
	Spring = 1
	Summer
	Autumn = 4
	Winter
End Enum
$vbLabelText   $csharpLabel

In this example, the Season enum has a byte as its underlying type. Spring is explicitly assigned a value of 1, making it the default value, while Summer, Autumn, and Winter are assigned corresponding values based on their order.

Using Enums in Your Code

To use an enum, you simply declare a variable of the specified enum type and assign it a value of the enum, such as one of the different values defined within the enum declaration, using dot syntax.

// Declare a Season variable and assign it an enum member value
Season currentSeason = Season.Autumn;
// Declare a Season variable and assign it an enum member value
Season currentSeason = Season.Autumn;
' Declare a Season variable and assign it an enum member value
Dim currentSeason As Season = Season.Autumn
$vbLabelText   $csharpLabel

This line creates a variable currentSeason of type Season and assigns it the value Autumn. This makes it clear that currentSeason can only hold a value that is a valid Season.

Converting Between Enum Values and Integers

You can convert an enum value to its corresponding integer value using casting, and vice versa. This is useful when you need to store or transmit data in its numeric form.

// Convert Season.Autumn to its integer value and vice versa
int autumnInt = (int)Season.Autumn;     // autumnInt will be 4
Season season = (Season)4;              // season will be Season.Autumn
// Convert Season.Autumn to its integer value and vice versa
int autumnInt = (int)Season.Autumn;     // autumnInt will be 4
Season season = (Season)4;              // season will be Season.Autumn
Imports System

' Convert Season.Autumn to its integer value and vice versa
Dim autumnInt As Integer = CInt(Math.Truncate(Season.Autumn)) ' autumnInt will be 4
Dim season As Season = CType(4, Season) ' season will be Season.Autumn
$vbLabelText   $csharpLabel

Here, autumnInt will have the value 4, which corresponds to Autumn in the Season enum. Conversely, season will be set to Autumn when casting the integer 4 back to a Season.

Working with Enum Methods

C# provides several methods for working with enums, such as Enum.GetName(), Enum.GetNames(), Enum.GetValue(), and Enum.GetValues(), which are useful for accessing the int constants associated with each enum member.

// Get names of all enum members and print them
string[] names = Enum.GetNames(typeof(Season));
foreach (string name in names)
{
    Console.WriteLine(name);
}
// Get names of all enum members and print them
string[] names = Enum.GetNames(typeof(Season));
foreach (string name in names)
{
    Console.WriteLine(name);
}
' Get names of all enum members and print them
Dim names() As String = System.Enum.GetNames(GetType(Season))
For Each name As String In names
	Console.WriteLine(name)
Next name
$vbLabelText   $csharpLabel

C# Enums (How It Works For Developers): Figure 1 - Console output of the each value associated with Season enum

This code snippet prints the names of all members of the Season enum. Such methods are incredibly useful for iterating over all possible values of an enum or converting between the string representation and the enum value.

Assigning Specific Values to Enum Members

You can assign specific integer values to enum members to control their numeric value explicitly.

// Define an enum with custom integer values for members
enum ErrorCode : int { None = 0, NotFound = 404, Unauthorized = 401 }
// Define an enum with custom integer values for members
enum ErrorCode : int { None = 0, NotFound = 404, Unauthorized = 401 }
' Define an enum with custom integer values for members
Friend Enum ErrorCode As Integer
	None = 0
	NotFound = 404
	Unauthorized = 401
End Enum
$vbLabelText   $csharpLabel

In this example, ErrorCode is an enum with custom integer values assigned to each member. This is useful for predefined numeric codes, such as HTTP status codes.

Using Enums as Bit Flags

By using the [Flags] attribute, you can define an enum as a set of bit flags. This allows you to store a combination of values in a single enum variable.

[Flags]
// Define an enum for permissions using bit flags
enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 }
[Flags]
// Define an enum for permissions using bit flags
enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 }
' Define an enum for permissions using bit flags
<Flags>
Friend Enum Permissions
	None = 0
	Read = 1
	Write = 2
	Execute = 4
End Enum
$vbLabelText   $csharpLabel

With the Permissions enum defined above, you can combine different permissions using the bitwise OR operator.

// Combine permissions using bitwise OR
Permissions myPermissions = Permissions.Read | Permissions.Write;
// Combine permissions using bitwise OR
Permissions myPermissions = Permissions.Read | Permissions.Write;
' Combine permissions using bitwise OR
Dim myPermissions As Permissions = Permissions.Read Or Permissions.Write
$vbLabelText   $csharpLabel

This sets myPermissions to a combination of Read and Write permissions.

Enum and Switch Statements

Enums work exceptionally well with switch statements, allowing you to execute different code blocks based on the enum's value.

// Use a switch statement with an enum
Season season = Season.Summer;
switch (season)
{
    case Season.Spring:
        Console.WriteLine("It's spring.");
        break;
    case Season.Summer:
        Console.WriteLine("It's summer.");
        break;
    case Season.Autumn:
        Console.WriteLine("It's autumn.");
        break;
    case Season.Winter:
        Console.WriteLine("It's winter.");
        break;
}
// Use a switch statement with an enum
Season season = Season.Summer;
switch (season)
{
    case Season.Spring:
        Console.WriteLine("It's spring.");
        break;
    case Season.Summer:
        Console.WriteLine("It's summer.");
        break;
    case Season.Autumn:
        Console.WriteLine("It's autumn.");
        break;
    case Season.Winter:
        Console.WriteLine("It's winter.");
        break;
}
' Use a switch statement with an enum
Dim season As Season = Season.Summer
Select Case season
	Case Season.Spring
		Console.WriteLine("It's spring.")
	Case Season.Summer
		Console.WriteLine("It's summer.")
	Case Season.Autumn
		Console.WriteLine("It's autumn.")
	Case Season.Winter
		Console.WriteLine("It's winter.")
End Select
$vbLabelText   $csharpLabel

This code will print "It's summer." because the season variable is set to Season.Summer.

Parsing String to Enum

C# allows you to parse a string to get the corresponding enum value using the Enum.Parse() method.

// Parse a string into an enum value
string input = "Winter";
Season season = (Season)Enum.Parse(typeof(Season), input);
// Parse a string into an enum value
string input = "Winter";
Season season = (Season)Enum.Parse(typeof(Season), input);
' Parse a string into an enum value
Dim input As String = "Winter"
Dim season As Season = DirectCast(System.Enum.Parse(GetType(Season), input), Season)
$vbLabelText   $csharpLabel

This code converts the string "Winter" to its corresponding enum value Season.Winter.

Integrating IronPDF with Enums in C#

IronPDF PDF Library for Dynamic Document Generation is a PDF library for .NET applications that helps developers create, edit, and manipulate PDF documents with ease. This powerful library can be particularly useful in scenarios where dynamic PDF generation is required, such as generating reports or invoices. In this section, we'll explore how to integrate IronPDF with C# enums for creating PDF reports from HTML in .NET, and we'll also cover the installation process of IronPDF in your project.

With IronPDF, you can turn any HTML, URL, or webpage into a PDF that looks exactly like the source. It’s a great option for generating PDFs for invoices, reports, and other web-based content. Ready to convert HTML to PDF? IronPDF makes it effortless.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Installing IronPDF

Installation of IronPDF is very easy using the NuGet package manager console. Open the package manager console in Visual Studio and write the following command:

Install-Package IronPdf

This command will install IronPDF in our project.

An alternative way is to install IronPDF in your project utilizing Visual Studio. In Visual Studio, right-click on the solution explorer and click on NuGet Package Manager for Solutions. Afterward, click the browse tab on the left side. Then, search for IronPDF, click install, and add it to your project.

C# Enums (How It Works For Developers): Figure 2 - Install IronPDF by searching "IronPDF" using the NuGet Package Manager

Using IronPDF with Enums

Let’s consider a scenario where you want to generate a PDF document that includes a report on seasonal sales data. You can use enums to represent different seasons and IronPDF to generate the PDF report. First, define an enum for the seasons:

public enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}
public enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}
Public Enum Season
	Spring
	Summer
	Autumn
	Winter
End Enum
$vbLabelText   $csharpLabel

Next, we’ll write a method that generates a PDF report based on the selected season. This method will utilize IronPDF to create a simple PDF document that outlines sales data for the given season.

using IronPdf;
public class SalesReportGenerator
{
    public static void GenerateSeasonalSalesReport(Season season)
    {
        IronPdf.License.LicenseKey = "License-Key";
        var Renderer = new IronPdf.ChromePdfRenderer();
        var htmlTemplate = $"<h1>Sales Report for {season}</h1><p>This section contains sales data for the {season} season.</p>";
        var pdf = Renderer.RenderHtmlAsPdf(htmlTemplate);
        var outputPath = $@"{season}SalesReport.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF report generated: {outputPath}");
    }
}
using IronPdf;
public class SalesReportGenerator
{
    public static void GenerateSeasonalSalesReport(Season season)
    {
        IronPdf.License.LicenseKey = "License-Key";
        var Renderer = new IronPdf.ChromePdfRenderer();
        var htmlTemplate = $"<h1>Sales Report for {season}</h1><p>This section contains sales data for the {season} season.</p>";
        var pdf = Renderer.RenderHtmlAsPdf(htmlTemplate);
        var outputPath = $@"{season}SalesReport.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF report generated: {outputPath}");
    }
}
Imports IronPdf
Public Class SalesReportGenerator
	Public Shared Sub GenerateSeasonalSalesReport(ByVal season As Season)
		IronPdf.License.LicenseKey = "License-Key"
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim htmlTemplate = $"<h1>Sales Report for {season}</h1><p>This section contains sales data for the {season} season.</p>"
		Dim pdf = Renderer.RenderHtmlAsPdf(htmlTemplate)
		Dim outputPath = $"{season}SalesReport.pdf"
		pdf.SaveAs(outputPath)
		Console.WriteLine($"PDF report generated: {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

In this example, we define a method GenerateSeasonalSalesReport that takes a Season enum as a parameter. It uses IronPDF's ChromePdfRenderer class to generate a PDF from an HTML string that includes the season name and a placeholder text for sales data. The PDF is then saved with a filename that includes the season name.

Execution

To generate a seasonal sales report, call the GenerateSeasonalSalesReport method with a specific season:

static void Main(string[] args)
{
    SalesReportGenerator.GenerateSeasonalSalesReport(Season.Winter);
}
static void Main(string[] args)
{
    SalesReportGenerator.GenerateSeasonalSalesReport(Season.Winter);
}
Shared Sub Main(ByVal args() As String)
	SalesReportGenerator.GenerateSeasonalSalesReport(Season.Winter)
End Sub
$vbLabelText   $csharpLabel

This call generates a PDF document named WinterSalesReport.pdf, which includes the sales report for the winter season.

C# Enums (How It Works For Developers): Figure 3 - Example PDF output using IronPDF from the code example

Conclusion

Enums in C# offer a type-safe way to work with sets of related named constants. They enhance code readability, reduce errors, and facilitate cleaner code organization. By grouping related constant values under a meaningful name, enums make your code easier to understand and maintain.

Integrating IronPDF with enums in C# allows for the dynamic generation of PDF documents based on enumerated types. IronPDF offers a free trial of its comprehensive PDF tools, providing a range of options to fit different project needs and scales.

Häufig gestellte Fragen

Was sind Enums in C# und warum sind sie nützlich?

Enums, kurz für Enumerationen, sind eine Funktion in C#, die es Entwicklern ermöglicht, eine Menge benannter Konstanten zu definieren. Dies verbessert die Code-Lesbarkeit und Wartung, da konstante Werte unter einem Namen gruppiert werden.

Wie deklariert und initialisiert man ein Enum in C#?

In C# deklarieren Sie ein Enum mit dem enum-Schlüsselwort, gefolgt vom Enum-Namen und seinen Mitgliedern. Zum Beispiel erstellt enum Season { Spring, Summer, Autumn, Winter } ein Enum namens Season mit vier Mitgliedern.

Können Enum-Mitglieder in C# benutzerdefinierte zugrundeliegende Werte haben?

Ja, Sie können Enum-Mitgliedern in C# bestimmte Ganzzahlen zuweisen, was es Ihnen ermöglicht, ihre numerische Darstellung zu steuern. Zum Beispiel weist enum ErrorCode { None = 0, NotFound = 404, Unauthorized = 401 } jedem Mitglied benutzerdefinierte Werte zu.

Wie konvertiert man einen Enum-Wert in eine Ganzzahl und umgekehrt in C#?

Um einen Enum-Wert in eine Ganzzahl zu konvertieren, verwenden Sie Casting, wie (int)Season.Autumn. Um eine Ganzzahl in ein Enum zu konvertieren, casten Sie die Ganzzahl in den Enum-Typ, wie (Season)4.

Was ist der Zweck des [Flags]-Attributs in C#-Enums?

Das [Flags]-Attribut in C# erlaubt es, ein Enum als eine Menge von Bit-Flags zu verwenden, wodurch Kombinationen von Werten in einer einzigen Variablen ermöglicht werden. Dies ist nützlich für Szenarien, in denen mehrere Werte zusammen dargestellt werden müssen, wie z.B. das Kombinieren von 'Read'- und 'Write'-Berechtigungen.

Wie kann man Enums zur Erstellung dynamischer PDF-Dokumente in C# nutzen?

Enums können verwendet werden, um verschiedene Kategorien oder Typen bei der dynamischen PDF-Dokumentenerstellung darzustellen. Beispielsweise kann ein 'Season'-Enum verwendet werden, um PDFs für saisonale Verkaufsberichte zu erstellen, indem der entsprechende Enum-Wert ausgewählt wird, um den Inhalt dynamisch anzupassen.

Was ist der Prozess zur Installation einer Bibliothek zur PDF-Erstellung in einem C#-Projekt?

Um eine PDF-Erstellungsbibliothek in einem C#-Projekt zu installieren, verwenden Sie die NuGet-Paketmanager-Konsole mit einem Befehl wie Install-Package [LibraryName], oder verwenden Sie die NuGet-Paketmanagement-oberfläche von Visual Studio für die Installation.

Wie können Enums mit Switch-Anweisungen in C# implementiert werden?

Enums können mit Switch-Anweisungen verwendet werden, um verschiedene Codeblöcke basierend auf dem Enum-Wert auszuführen. Zum Beispiel kann eine Switch-Anweisung auf einer 'Season'-Enum-Variablen spezifische Logik für jede Jahreszeit ausführen, was die Code-Klarheit und Organisation verbessert.

Wie analysiert man eine Zeichenkette in ein Enum in C#?

Um eine Zeichenkette in einen Enum-Wert in C# zu analysieren, können Sie die Methode Enum.Parse() verwenden. Beispielsweise konvertiert Enum.Parse(typeof(Season), "Winter") die Zeichenkette 'Winter' in ihren entsprechenden Enum-Wert 'Season.Winter'.

Welche Methoden stehen für die Arbeit mit Enum-Namen in C# zur Verfügung?

C# bietet Methoden wie Enum.GetName() und Enum.GetNames(), um mit Enum-Namen zu arbeiten. Enum.GetName() gibt den Namen der Konstante zurück, die den angegebenen Wert hat, während Enum.GetNames() ein Array der Namen aller Konstanten im Enum zurückgibt.

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