jeudi 12 décembre 2019

How does 2D-array casting work in C#? (and why not always)

How is this possible:

    DivideByZeroException[,] a = new DivideByZeroException[,] { { new DivideByZeroException() } };
    ArithmeticException[,] b = a;   // a = b; is not possible

while all these:

    typeof(DivideByZeroException[,]).IsInstanceOfType(typeof(ArithmeticException[,]))   // false
    typeof(DivideByZeroException[,]).IsSubclassOf(typeof(ArithmeticException[,]))   // false
    typeof(DivideByZeroException[,]).IsAssignableFrom(typeof(ArithmeticException[,]))   // false
    TypeDescriptor.GetConverter(typeof(DivideByZeroException[,])).CanConvertTo(typeof(ArithmeticException[,]))  // false
    TypeDescriptor.GetConverter(typeof(ArithmeticException[,])).CanConvertFrom(typeof(DivideByZeroException[,]))  // false

return false?

And if so, why is this below not possible?

    int[,] x = new int[,] { { 123 } };
    float[,] y = x;

How does the 2D array casting work in C#?

Is it some hidden implicit operator somewhere? (Can implicit operator be generic?? I thought not!)

Is it a hidden language syntax feature?

If you would be trying to convert the value from one type to another by Reflection (while not understanding the both types), how can you know if the conversion is possible and how would you convert it?





Aucun commentaire:

Enregistrer un commentaire