© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
3 replies
Hugh

✅ Casting to enum when only having a Type object

Does anyone know how it's possible to cast while only having a
Type
Type
object, and not the actual type at compile time?

I've got an enum (
MyEnum
MyEnum
), and an integer value (
value
value
)

I want to do the equivalent of this:
object? newValue = (MyEnum)value;
object? newValue = (MyEnum)value;


While only having access to
typeof(MyEnum)
typeof(MyEnum)
and not knowing what
MyEnum
MyEnum
actually is.

I had thought I could do this:

object? newValue = Convert.ChangeType(value, typeof(MyEnum));
object? newValue = Convert.ChangeType(value, typeof(MyEnum));


But this errors saying: `System.InvalidCastException: Invalid cast from 'System.Int32' to 'MyEnum'.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Casting object to enum class
C#CC# / help
2y ago
✅ Type Casting
C#CC# / help
4y ago
When to use object or dynamic type
C#CC# / help
4y ago
✅ Safe type casting with LINQ?
C#CC# / help
3y ago