3

enum makes Code more readable and easy to understand in many case. But I can't understand 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 any source code sample where can I used this type of enum Array.

usr
  • 168,620
  • 35
  • 240
  • 369
Mithun
  • 65
  • 1
  • 9
  • 1
    It's just a sample. My main question is to use this type of enum array like " A[] aa = (A[])(Array) new B[100]; " You can give any code none but must have enum array casting like that – Mithun Jun 13 '15 at 18:17

1 Answers1

2

The CLR has more generous casting rules than C# has. Apparently, the CLR allows to convert between arrays of enums if the underlying type has the same size for both types. In the question that I linked the case was (sbyte[])(object)(byte[]) which is similarly surprising.

This is in the ECMA spec Partition I I.8.7 Assignment compatibility.

underlying types – in the CTS enumerations are alternate names for existing types (§I.8.5.2), termed their underlying type. Except for signature matching (§I.8.5.2)

III.4.3 castclass says

If the actual type (not the verifier tracked type) of obj is verifier-assignable-to the type typeTok the cast 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 being created. It really is just a cast of the object reference.

Community
  • 1
  • 1
usr
  • 168,620
  • 35
  • 240
  • 369
  • 1
    Basically, while it isn't "type-safe", it is memory-access safe, because array bounds checking will prevent access off the end of the array, so long as the true type and the type used for access are the same size. Since you can't harm the runtime, only your own data, .NET allows it if you insist. – Ben Voigt Jun 13 '15 at 19:34