Sunday, December 29, 2019
Understanding Usage of Generic Types in Delphi
Generics, a powerful addition to Delphi, were introduced in Delphi 2009 as a new language feature. Generics or generic types (also know as parametrized types), allow you to define classes that dont specifically define the type of certain data members. As an example, instead of using the TObjectList type to have a list of any object types, from Delphi 2009, the Generics. Collections unit defines a more strongly typed TObjectList. Heres a list of articles explaining generic types in Delphi with usage examples: What and Why and How on Generics in Delphi Generics with Delphi 2009 Win32 Generics are sometimes called generic parameters, a name which allows to introduce them somewhat better. Unlike a function parameter (argument), which has a value, a generic parameter is a type. And it parameterizes a class, an interface, a record, or, less frequently, a method ... With, as a bonus, anonymous routines and routine references Delphi Generics Tutorial Delphi tList, tStringList, tObjectlist or tCollection can be used to build specialized containers, but require typecasting. With Generics, casting is avoided and the compiler can spot type errors sooner. Using Generics in Delphi Once youââ¬â¢ve written a class using generic type parameters (generics), you can use that class with any type and the type you choose to use with any given use of that class replaces the generic types you used when you created the class. Generic Interfaces in Delphi Most of the examples Iââ¬â¢ve seen of Generics in Delphi use classes containing a generic type. However, while working on a personal project, I decided I wanted an Interface containing a generic type. Simple Generics Type Example Heres how to define a simple generic class: typeTGenericContainerT classValue : T;end; With the following definition, heres how to use an integer and string generic container: vargenericInt : TGenericContainerinteger;genericStr : TGenericContainerstring;begingenericInt : TGenericContainerinteger.Create;genericInt.Value : 2009; //only integersgenericInt.Free;genericStr : TGenericContainerstring.Create;genericStr.Value : Delphi Generics; //only stringsgenericStr.Free;end; The above example only scratches the surface of using Generics in Delphi (does not explain anything though - but above articles have it all you want to know!). For me, generics were the reason to move from Delphi 7 / 2007 to Delphi 2009 (and newer).
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.