E-Learning

Learn C# – How To Get Int Value from Enum?

c# int value enum

Getting an int value from enum can be challenging in C#. However, it can easily be done by using the following code:

The above code stores int value of Months enum into abc.

We have used Typecasting to get the int value from Enum. Yes, it is as easy at it can get. But, didn’t we say it can be challenging? Let’s get to the challenging part.

If you don’t know what integral type is used (for example, int, byte, short, etc.), you can become stuck..

For example, enum is declared as below.

To get WeInt from the enum DifferentType, you need to use the following line of code:

long getWeInt = (long)DifferentType.WeInt

Either you need to know which integer type is used, or declare it as static class and know the constraints in it.

Let’s see an example of how it can be implemented.

Now, you can just call Learning.power to get the value 2 without worrying about typecasting the right integer value.

However, you might want to use readonly as compiler tends to change them to hard values. You can read more about it here.

Another way of handling the underlying integer type.

If you don’t want to use const or readonly, then you can use GetTypeCode() method and convert a class to get your work done.

And, that’s all for getting the int value from Enum. If you have any questions or feedback, use the comment section below.

You can also check on our website videos about C#. Below are some examples:

  • C# – Colossal Cave Adventure port – C#

  • Application Control of Acess in Real Time (part 2) – C#

You can also follow some of our broadcasters who program in C#, below:

 MauricioR

 David

Another cool way to find out interesting things about C# is to access our project page!

About author

About Author Dr. Michael Jurgen Garbade is the founder of LiveEdu.TV, Kyuda, Education Ecosystem. He is future Venture Capitalist, Future Politician and always on the lookout for the Next Big Challenge. Obtained Masters in business administration and physics, and a Ph.D. in finance with professional work experience in high-paced environments at Fortune 500 companies like Amazon and General Electric. Expertize: Python, PHP, Sencha Touch & C++, SEO, Finance, Strategy & E-commerce. He speaks English and German and has worked in the US, Europe, and Asia. At Education Ecosystem he is the CEO and runs business operations.
Related posts
Career DevelopmentContent Creators

Meet Yuzby, An Inspiring Developer From Nigeria

Data Science

R Tutorial for Data Science Part 1

Content CreatorsCryptocurrency

Main Technical Differences between Tron, VET, NEO and Ethereum Blockchains

Coding Community

Google's Go Programming Language Is Going Places—By How Far?