Comrades, tell me, please

static void Main() { object [] A = new string[3] { "1", "2", "3" }; Console.WriteLine(A[1]); } 

Why is the value of 1 index displayed? After all, in theory, it should not be displayed, since object is just a base class, and string is derived from it. But the base class does not have access to the elements of the derivative, except for those that themselves were inherited from the base. That is, it turns out that the objekt should not access the array.

Here, for example, it is correct that there is no access

 using System; class a { public int x = 9; } class b : a { public new int x = 88; } class c : b { public new int x = 388; } class d { static void Main() { object a = new c(); Console.WriteLine(ax); } } 
  • and in what the contradiction? In the first case, you do not apply to any methods at all - neither to descendant methods, nor to ancestral methods, and everything works. In the second case, you declare a as an object , and then try to work with it as with the class c . Although in fact your a variable is an instance of c , the compiler does not know about it, since you declared it as an object . Everything is logical - DreamChild
  • Such a question - why do we need the covariance of arrays at all? - Veikedo
  • > The question is: why is covariance of arrays needed at all? @Veikedo and to whom is this question addressed? If to the vehicle, then in his case most likely it was applied unconsciously as part of the example - DreamChild
  • @DreamChild, to whom specifically. Just a lyrical digression :) - Veikedo
  • 2
    @Veikedo well, if within the framework of a lyrical digression, then such a notorious comrade, like Eric Lippert, reasonably argued against the covariance of arrays, it weakens type safety. However, now nobody will cut it out of the language - DreamChild

1 answer 1

Because the Object.ToString () method is called, which casts the current object into a String. But this is forehead and not true.

And to be honest, the polymorphic String.ToString () method is not ideologically correctly called.

  • one
    Why idiot? - Veikedo
  • > the Object.ToString () method is called, which casts the current object in the String I would not argue that it is coerced to a string - DreamChild
  • @Veikedo Because String.ToString () has little sense in itself. Do not take to heart, I am figuratively and without malice =) - free_ze
  • @DreamChild> But this is head-on and not true. =) MSDN agrees with you. - free_ze
  • one
    @DreamChild Because I went to investigate the subject of the discussion more deeply and corrected myself) But someone has already hurried to agree with my erroneous assumption, because the old version was not removed, but stressed its fallacy. - free_ze