2005-09-14
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 3 of 3 )
The Solution
Parameterized methods in C# use a named parameter between the < and > characters. In Listing 1, T is the parameter name. (Using the name T is a popular convention carried over from the C++ programming language.) In the listing, arguments a and b and the local variable temp are declared as the parameterized type T. When Swap is called, we provide the type of T. For all intents and purposes, all instances of the parameterized type are substituted with the stipulated type (in the example, a string).
Generics in C# add a refinement to parameterized types, the where predicate, which leads us to the correction of the code above. The where predicate permits us to stipulate limitations on the parameterized type. In the example, where T : struct means that all uses of Swap depend on T being a value type that is non-nullable. The error the compiler will report is that T must be non-nullable, but strings are nullable. That is, strings can be assigned to the literal null. An example of a non-nullable type is int (the Integer type). If we had used an integer in the example in Listing 1, the code would compile without error.
Note: Non-nullable types, such as integers, can be converted to nullable types by adding the ? suffix to the type declaration. For example, int? means that a type can be assigned to null. This feature is desirable when working with nullable database types. For instance, an integer in a database can be null, but assigning a null database integer field to a non-nullable .NET integer type causes an exception. Converting the int to a nullable int (int?) avoids the database exception.
To fix the problem encountered in Listing 1, we could remove the where predicate. If we explicitly meant to permit reference types and not value types, then we could replace struct with class.
Eyeballing code and quickly detecting an error is a valuable skill. Sometimes, however, programmers are too close to their own code, and need a second set of eyes to find problems. You may be that second set of eyes. Quickly being able to spot code problems will help you be an invaluable asset to your peers and to your employer.
![]() |
|


