Generic Types Compatibility Rules

In traditional Pascal and in Delphi's Object Pascal the core type compatibility rules are based on type name equivalence. In other words, two variables are type compatible only if their type name is the same, regardless of the actual data structure they refer two.

This is a classic example of type incompatibility with arrays (part of the TypeCompRules example): type

TArrayOf10 = array [1..10] of Integer;

procedure TForm30.ButtonlClick(Sender: TObject); var arrayl: TArrayOflO; array2: TArrayOflO

array3, array4: array [1..10] of Integer; begi n arrayl := array2;

// E20l0 Incompatible types: 'TArrayOflO' and 'Array'

array3 := array4;

// E20l0 Incompatible types: 'Array' and 'TArrayOfW end;

As you can see in the code above, all four arrays are structurally identical. However, the compiler will let you assign only those that are type compatible, either because their type has the same explicit name (like TArrayOfl0) or because they have the same implicit (or compiler generated, type name, as the two arrays declared in a single statement.

This type compatibility rule has very limited exceptions, like those related to derived classes. A new exception to the rule, and a very significant one, is type compatibility for generic types, which is probably also used internally by the compiler to determine when to generate a new type from the generic one, with all of its methods.

The new rule states that generic types are compatible when the share the same generic class definition and instance type, regardless of the type name associated with this definition. In other words, the full name of the generic type instance is a combination of the generic type and the instance type.

In the following example the four variables are all type compatible:

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment