Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Non-Integer enums and Casting

C# allows you to assign values to your enum elements such as

public enum Animals
{
    Dog = 0, Cat = 1,
}

And You can cast too and from them like so.

public void demo()
{
    int dog = (int)Animals.Dog;
    Animals cat = (Animals)(dog++);
}

But c# also lets you do things like this

public enum Animals
{
    Dog = Vector2.One, Cat = Vector2.Zero,
}

However you cannot get the Vector2 back in and out with a cast. such as

Vector2 dog = (Vector2)Animals.Dog; //this fails

Is this problem solvable? *Note Vector2 is a class object and Vector2.One and Vector2.Zero are static declarations of such. Which means Dog is assigned to a memory reference.

like image 966
ohmusama Avatar asked Feb 20 '26 11:02

ohmusama


1 Answers

The only way that C# will let you do

public enum Animals
{
    Dog = Vector2.One,
    Cat = Vector2.Zero
}

Is if there is an implicit cast from Vector2 to an integral type. Otherwise, you will get a compile error. This is why you cannot cast back to Vector2 - there is no cast from int back to Vector2. Dog and Cat are integer valued, and the values come from the implicit cast from Vector2.One and Vector2.Zero to int, respectively.

You could define your own explicit cast to make it work, but I'm guessing you won't be able to get back all the information you want that way.

like image 118
David Merriman Avatar answered Feb 22 '26 23:02

David Merriman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!