C# Enums (How It Works For Developers)

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 IronPDF library.

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.

enum Season { Spring, Summer, Autumn, Winter }
enum Season { Spring, Summer, Autumn, Winter }
Friend Enum Season
	Spring
	Summer
	Autumn
	Winter
End Enum
VB   C#

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.

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
VB   C#

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.

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 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
VB   C#

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 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)
VB   C#

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.

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
VB   C#

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.

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
VB   C#

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]
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
VB   C#

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
VB   C#

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.

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
VB   C#

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.

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)
VB   C#

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

Integrating IronPDF with Enums in C#

IronPDF 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 PDF generation, and we'll also cover the installation process of IronPDF in your project.

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
VB   C#

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
VB   C#

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
VB   C#

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 start from $749, providing a range of options to fit different project needs and scales.