Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
How to cast a variable of an enum generic type to int and back

I am using C# to write a class that takes an enum type parameter, like this:

class EnumWrapper<T>
    where T: Enum
{
}

Inside the class, I have a method that takes an argument of type T, and I need to cast it to an int, like this:

void DoSomething(T arg)
{
    int a = (int)arg;
}

But the compiler issues a CS0030 error "Cannot convert type 'T' to 'int'. Something similar happens when I try to cast an int back into a T. However, this works with a fixed enum type that is not provided via a type parameter. For example, this works fine:

void DoSomething(DayOfWeek arg)
{
    int a = (int)arg;
}

Why is this happening, and how can I cast between a generic enum type and int?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You may add IConvertible to generic constraint and use ToInt32 method, something like

class EnumWrapper<T>
    where T : Enum, IConvertible
{
    void DoSomething(T arg)
    {
        int a = arg.ToInt32(null);
    }
}

Have a look at the Enum constraint for details. Also, as mentioned in comments, it isn't necessary that your enum is based on int type

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!