Often you'll hear someone say something like, "one of the ways that C# and VB will diverge in the future is that C# will support generics". Well, both C# and VB will support generics in the Whidbey release. The second thing you'll likely hear is someone asking, "what is a generic?"
The best explanation I've heard (from Don Box) is that generics are simply "types with holes" that can be filled by the caller. A simple example would be a type that compares two values and returns the larger of the two (adapted from this article):
public class Compare<ItemType, ItemType>
{
public ItemType Larger(ItemType data, ItemType data2)
{
// logic...
}
}
Compare<int, int> compare = new Compare<int, int>;
int MyInt = compare.Larger(3, 5);
The caller can then redeclare the Compare class using floats or some other data type instead of integers. While this can be done using System.Object generics will perform better since boxing and unboxing are not required (see this article for an overview of how much this costs).
No comments:
Post a Comment