New Features in C# 2.0—Type-Safe List: What about
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Tutorials |
| C# Tutorials |
| © 2005 O'Reilly Media, Inc. |
What about
if you try to add an integer to the list of Employees?
Try it. Start by uncommenting the following line in Example 1-1 and recompiling the program:
empList.Add(i * 5);
You’ll get a pair of compile errors:
Error 1 The best overloaded method match for 'System.Collections.
Generic.List<ListCollection.Employee>.Add(ListCollection.Employee)'
has some invalid arguments
Error 2 Argument '1': cannot convert from 'int' to
'ListCollection.Employee'
The information provided in these two compile errors enable you to
determine that it is not legal to add an int to a collection of Employee objects because no implicit conversion or subtype relationship exists from
one to the other.
The good news is that this is a compile error, rather than a runtime error, which can sneak out the door and happen only when your client runs the application!
what about other generic collections; are any available?
Other generic collections are available as well. For instance, the Stack
and Queue collections, as well as the ICollection interface, are available in type-safe versions in .NET 2.0.
You use these just as you would List<T>. For example, to make a stack of
Employee objects, you replace T in the Stack definition (Stack<T>) with
the Employee type:
Stack<Employee> employeeStack = new Stack<Employee>( );
You can store derived types in a type-safe collection. Thus, a collection of Employees will hold a Manager object, if Manager derives from Employee.
|
|

