Thursday, May 24, 2007

So what are generics anyway?

A lot Delphi developers 'demand' generics to be added to the Delphi language, or should I say Object Pascal. Question that pops up is, What are generics anyway?

Generics where introduced in .NET framework 2.0 in the C# language. Simply said they are collections(lists) which are type safe, i.o.w. you can detect type mismatches at compile time. With other structures (arrays etc) you must check the type in runtime and then type cast to the appropiate type. So generics will make your apps more robust in a way.

Lately I have used the C# language a lot so I learned the power of generics.
Let's take a look at it!

A generic list is declared like this:
System.Collections.Generic.List<MyItem> MyItems;

Between the brackets you specify the name of the class which will be hold by the list. The compiler expects objects of this type. If you add a different type you will get a compiler error.

An example:
Suppose you have a class MyItem which looks like this:

public class MyItem
{
string FName;
public MyItem()
{
}

public string Name
{
get
{
return FName;
}
set
{
FName = value;
}
}
}
You can now fill the collection(or should I say List?) FItems like this:

MyItem Item = new MyItem();
Item.Name = "First";
FItems.Add(Item);
MyItem Item = new MyItem();
Item.Name = "Second";
FItems.Add(Item);
We now have a list with two MyItem objects.

You can search within the list using the Find and Findall methods.
Suppose you want the second object you could find it like this:

MyItem SearchedItem = MyItems.Find(delegate(MyItem SItem)
{
return SItem.Name == "Second";
});
Through a anonymous delegate it returns the object which matches the criteria. The Findall method returns a list with objects, for example all objects where a specific attribute matches.
There is a lot more to explore, for more information look at the MSDN website.

Generics and Delphi
Generics are planned for the Delphi Highlander release, later this year (Roadmaps coming in june!). In september 2006 Nick Hodges showed at the EKon 10 / BorCon Europe conference a preview of the syntax. Bob Swart has published a few notes about it here.

4 comments:

Tate said...

Are generics in .NET what class Templates where in C++?

Anonymous said...

--tate
They are related, but there is a difference. See here http://www.codeproject.com/csharp/Generics_Explained.asp#_GenericsTemplatesDiff

Anonymous said...

In my opinion, generics are poor implementation of C++ templates imposed as standard by powerful company.

Clearer said...

Generics have also been present in Java since version 1.5 (or Java 5 if you want).