Why can I use A [] for B [] if A and B are enum types?

enum makes the code easier to understand and understand in many cases. But I cannot figure out when I can use this line like below:

public enum A
{
    apple,orange,egg
}
public enum B
{
    apple,orange,egg
}
public static void main()
{
    A[] aa = (A[])(Array) new B[100];
}

      

Can anyone give me a sample source code where I can use this type of enum array.

+3


source to share


1 answer


The CLR has more generous casting rules than C #. Apparently the CLR allows converting between arrays of enums if the underlying type is the same size for both types.In the question I linked it was (sbyte[])(object)(byte[])

, which is surprising too.

This is in the ECMA specification Section I.8.7 Assignment Compatibility.

base types - CTS enumerations have alternative names for existing types (ยงI.5.5.2), called their base type. Except signature match (ยงI.8.5.2)

III.4.3 castclass says



If the actual type (not tracked by the type verifier) โ€‹โ€‹of obj is a typeTok-assignable verifier, the listing succeeds

castclass

is the instruction that the C # compiler uses to perform this cast.

The fact that the enum members are the same in your example has nothing to do with the problem. Also note that no new object is created. It's really just an object reference listing.

+2


source







All Articles