Main

Array Covariance in C# - could it cause trouble? #shorts

Do you know that arrays in C# are defined as covariant? That is a special case, and unique case in all the language. Here is how that works. We can assign this array of strings to a variable declared as an array of objects. Well, that is strange! And it can get even more interesting. We can assign elements of the array of objects to strings and nothing bad would happen. But we can also attempt an obviously criminal assignment by setting the array's element to an object which is not the string. This attempt will pass compilation, but fail at run time. It will cause an ArrayTypeMismatchException.

Zoran Horvat

11 months ago

Do you know that arrays in C# are defined as covariant? That is a special case, and unique case in all the language. Here is how that works. We can assign this array of strings to a variable declared as an array of objects. Well, that is strange! And it can get even more interesting. We can assign elements of the array of objects to strings and nothing bad would happen. But we can also attempt an obviously criminal assignment by setting the array's element to an object which is not the string. T
his attempt will pass compilation, but fail at run time. It will cause an ArrayTypeMismatchException.

Comments

@maboroshi1687

I just found a new way to confuse my colleagues 😈

@kantagara

I have a question, What software do you use to record such a small screen space in fullHD? 😄

@rammrras9683

Great to know. But why? 😅