New Features in C# 2.0—Collection Interfaces: What about

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

What about…

…the IComparable requirement? Why did Pilgrim and Node require IComparable, but the linked list did not?

To understand this, it’s important to note that both Pilgrims and Nodes must be compared; linked lists are not compared. Because the linked list is sorted by sorting its nodes, there is no need to compare two linked lists to see which one is "greater" than the other.

…what about passing generic types to a method; can I do that?

Yes, you can pass a generic type to a method, but only if the method is generic. In Example 1-3, you display the contents of the list of integers and the list of pilgrims with the following code:

Console.WriteLine("Integers: " + myLinkedList);
Console.WriteLine("Pilgrims: " + pilgrims);

You are free to create a method to take these lists and display them (or manipulate them):

private void DisplayList<T>
  (string intro, LinkedList<T> theList) where T :
  IComparable<T>
{
  Console.WriteLine(intro + ": " + theList);
}

When you call the method, you supply the type:

DisplayList<int>("Integers", myLinkedList);
DisplayList<Pilgrim>("Pilgrims", pilgrims);


TIP
The compiler is capable of type inference, so you can rewrite the preceding two lines as follows:
DisplayList("Integers", myLinkedList);
DisplayList("Pilgrims", pilgrims);


Previous_Page_.gif Next_Page_.gif

Personal tools