enum Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/enum/ Everyone can code! Wed, 15 Jan 2020 03:03:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 209870635 How to cast int to enum in C# https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/ https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/#respond Wed, 15 Jan 2020 03:03:36 +0000 https://karthiktechblog.com/?p=326 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 post How to cast int to enum in C# appeared first on Learn Smart Coding.

]]>
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.

The post How to cast int to enum in C# appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/feed/ 0 326