Why does the backing store of an array bind to the smallest type?

In C# it is legal to write

Animal[] a = new Giraffe[4]; //with obvious relationships

Because arrays are covariant. However, this is a breaking relationship. It’s a runtime exception to then apply a different type of Animal to this array because the backing store is a Giraffe.

a[0] = new Cat(); //KABOOM

Why doesn’t the language create a covariant backing store? This doesn’t appear to be a limitation of the language because I can create this type of data structure myself:

class Program
{
    static void Main(string[] args)
    {
        A[] a = new B[2];
        a[0] = new B();
        a[1] = new C();//runtime exception

        var containerLegal = new Container<B, A>();
        containerLegal.Add(new B());
        containerLegal.Add(new C());//works fine
    }
}

class A { }

class B : A { }

class C : A { }

class Container<T,S> where T: class, S
{
    S[] s = new S[4];
    int currentIndex = 0;

    public void Add(S t)
    {
        s[currentIndex] = t;
        currentIndex++;
    }
}

I’m cheating a little bit cause I’m not using T in Container<>…but I think its a fair relationship anyhow.

1

The problem isn’t that you couldn’t store a reference to a C in that array (though I’m pretty sure it’s nontrivial to implement). The problem is, if you permit that, code like this (note that this can be spread out over several unrelated methods, due to arrays being reference types) becomes wrong:

B[] bs = new B[1];
A[] as = bs;
as[0] = new C();
B b = bs[0]; /* It's a C, but we use it as a B, and a C is not a B! */

How does it go wrong? Well, if it doesn’t notice and assumes a wrong object layout, you get all kinds of fun usually reserved for C, C++, and unsafe code:

  • Re-interpreting an int as a float (or a reference to T as a reference to U, for recursive instances of such fun).
  • Accessing uninitialized memory (or another object’s memory)
  • Calling a method with the wrong type or number of arguments.
  • Using padding bytes as if they has any meaning.
  • Overwriting metadata the GC/memory management system needs to operate.

Alternatively, you could restore safety by making all code reading from arrays do run-time type checks (as opposed to doing that check when writing to the array, as it currently does) and throwing an exception when an item has an unexpected type. That’s slow and you’d just get the same exception in a different place (when you access the reference vs. when you store it), so you didn’t “fix” anything.
That’s because you can’t fix it, such code is inherently broken. Your Container would exhibit the same problem if it permitted getting references back from the S[] (e.g., an indexer) unless it always returns the most general type (an S, not a T; otherwise you run into the same problem).

2

Because that’s what you told it to do. That is the equvalient of:

Girafe[] g = new Girafe[4];
Animal[] a = g;  // girafe array has been created by this time;

Your statement is clear about all types, if you let the left side determine the type of the right, you’d run into some problems. Consider..

Girafe[] g = GetGArray():
Animal[] a = GetGArray();

Does a equal g? If it doesn’t then a NEW backing store would have to be created, if it does, then the compiler would have to be determining what happens based upon whether it was a new or a function call. But then there is inlining…

Simpiliest to just do exactly what the line says.

2

As noted, arrays bind to whatever type is specified when they are created. The fact that even mutable arrays may be passed covariantly is a consequence of a few things:

  1. Arrays predate generics, and until covariant generics were added to .NET there was no immutable type which could behave covariantly, so the arrays (which were all mutable) were the only thing that could be covariant.

  2. To efficiently sort an array, one must be able to read items out of the array and write them back to it. If one has a reference of type Animal[], even if it points to a Cat[], one may without any possibility of run-time error read out any item of that array into a reference of type Animal and later store it back to the array from which it came. The ability to read out items might not be totally necessary if Array contained some methods like CopyItem and SwapItem, but being able to read out an item and write it back after performing many other changes to an array is more efficient than would be having to decompose every sort into a sequence of swaps. While one could design a covariant interface which would allow an array or other collection to be efficiently sorted without requiring the sorting code to directly write anything into the collection itself, it’s much easier to simply allow array covariance.

  3. An array knows the type of element it’s supposed to contain. This allows it to enforce type-safety at runtime. Although the generic collections added in .NET 2.0 also know their element type, most generic collections in Java don’t. If one tried to pass an ArrayList<Cat> to code expecting an ArrayList<Animal>, and if the latter code tried to add a Dog to it, there would be no way the ArrayList<Cat> could know that it was created as an ArrayList<Cat> and should reject the request.

If one declared arrays using syntax like Array<Dog> myDogs = new Array<Dog>(34); rather than Dog[] myDogs = new Dog[34];, then it might be possible to have multiple kinds of array references, so that e.g. Array<Animal> myDogs = new Array<Dog>(34); wouldn’t compile, but SortableArray<Animal> myDogs = new Array<Dog>(34); would. Neither Java nor .NET supports multiple array types, however.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật