How to cast int to enum in C#
How to cast int to enum in C#

Introduction

In this short post, I show How to cast int to enum in C#. We have used an enumeration type (or enum type) in our day to day programming. Enum is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, we used the enum keyword and specified the names of enum members as shown in below example.

public enum OrderStatus
{
Received = 1,
InProgress = 2,
Processed = 3,
Shipped = 4
}

How to convert int to enum ?

Let's take an example to demonstrate real time scenario. Consider we have a field that represents order status for a given product order.

public OrderStatus Status {get; set;}

OrderStatus is the enum that is defined with various status. E.g. Received, InProgress, Processed and Shipped.

Say you need to convert int or string to enum, it is easy to do so.

OrderStatus variableName = (OrderStatus)Enum.Parse(typeof(OrderStatus), yourStringVariable);

Yes, it is that easy to cast int to enum type.

Validate enum property in model

Say, your enum property needs to be validated in a given model, simple use the EnumDataType as shown below.

[Required]
[EnumDataType(typeof(OrderStatus), ErrorMessage = "Provide initial order status")]
public OrderStatus Status { get; set; }

Resource

Read more on Enum

Interested in Azure certification? Take a look at my post EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE

Conclusion

In this short post, I showed how to cast int or string to enum in C#. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights