Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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.
enum Season { Spring, Summer, Autumn, Winter }
enum Season { Spring, Summer, Autumn, Winter }
Friend Enum Season
Spring
Summer
Autumn
Winter
End Enum
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.
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.
enum Season : byte { Spring = 1, Summer, Autumn = 4, Winter }
enum Season : byte { Spring = 1, Summer, Autumn = 4, Winter }
Friend Enum Season As Byte
Spring = 1
Summer
Autumn = 4
Winter
End Enum
In this example, Season is an enum, referred to here as the enum name, with 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.
To use an enum, you simply declare a variable of the specified enum type and assign it a value of an enum, such as one of the different values defined within the enum declaration, using dot syntax.
Season currentSeason = Season.Autumn;
Season currentSeason = Season.Autumn;
Dim currentSeason As Season = Season.Autumn
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.
You can convert an enum value to its corresponding integer value using a given integral value, and vice versa. This is useful when you need to store or transmit data in its numeric form.
int autumnInt = (int)Season.Autumn;
Season season = (Season)4;
int autumnInt = (int)Season.Autumn;
Season season = (Season)4;
Imports System
Dim autumnInt As Integer = CInt(Math.Truncate(Season.Autumn))
Dim season As Season = CType(4, Season)
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.
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.
string[] names = Enum.GetNames(typeof(Season));
foreach (string name in names)
{
Console.WriteLine(name);
}
string[] names = Enum.GetNames(typeof(Season));
foreach (string name in names)
{
Console.WriteLine(name);
}
Dim names() As String = System.Enum.GetNames(GetType(Season))
For Each name As String In names
Console.WriteLine(name)
Next name
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.
You can assign specific integer values to enum members to control their numeric value explicitly.
enum ErrorCode : int { None = 0, NotFound = 404, Unauthorized = 401 }
enum ErrorCode : int { None = 0, NotFound = 404, Unauthorized = 401 }
Friend Enum ErrorCode As Integer
None = 0
NotFound = 404
Unauthorized = 401
End Enum
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.
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]
enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 }
[Flags]
enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 }
<Flags>
Friend Enum Permissions
None = 0
Read = 1
Write = 2
Execute = 4
End Enum
With the Permissions enum defined above, you can combine different permissions using the bitwise OR operator.
Permissions myPermissions = Permissions.Read | Permissions.Write;
Permissions myPermissions = Permissions.Read | Permissions.Write;
Dim myPermissions As Permissions = Permissions.Read Or Permissions.Write
This sets myPermissions to a combination of Read and Write permissions.
Enums work exceptionally well with switch statements, allowing you to execute different code blocks based on the enum's value.
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;
}
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;
}
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
This code will print "It's summer." because the season variable is set to Season.Summer.
C# allows you to parse a string to get the corresponding enum value using the Enum.Parse() method.
string input = "Winter";
Season season = (Season)Enum.Parse(typeof(Season), input);
string input = "Winter";
Season season = (Season)Enum.Parse(typeof(Season), input);
Dim input As String = "Winter"
Dim season As Season = DirectCast(System.Enum.Parse(GetType(Season), input), Season)
This code converts the string "Winter" to its corresponding enum value Season.Winter.
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.
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.
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
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
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.
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
This call generates a PDF document named WinterSalesReport.pdf, which includes the sales report for the winter season.
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.
9 .NET API products for your office documents