// The following statement would work only for reference types.
// The following statement will work only for numeric value types.
PART I
C h a p t e r 1 8 :
G e n e r i c s
523
PART IPART I
// This statement works for both reference and value types.
obj = default(T); // Works!
}
// ...
}
class DefaultDemo {
static void Main() {
// Construct Test using a reference type.
Test x = new Test();
if(x.obj == null)
Console.WriteLine("x.obj is null.");
// Construct Test using a value type.
Test y = new Test();
if(y.obj == 0)
Console.WriteLine("y.obj is 0.");
}
}
The output is shown here:
x.obj is null.
y.obj is 0.
Generic Structures
C# allows you to create generic structures. The syntax is the same as for generic classes. For
example, in the following program, the
XY
structure, which stores X, Y coordinates, is generic:
// Demonstrate a generic struct.
using System;
// This structure is generic.
struct XY {
T x;
T y;
public XY(T a, T b) {
x = a;
y = b;
}
public T X {
get { return x; }
set { x = value; }
}
public T Y {
get { return y; }
www.freepdf-books.com
524
P a r t I :
T h e C # L a n g u a g e
set { y = value; }
}
}
class StructTest {
static void Main() {
XY xy = new XY(10, 20);
XY xy2 = new XY(88.0, 99.0);
Console.WriteLine(xy.X + ", " + xy.Y);
Console.WriteLine(xy2.X + ", " + xy2.Y);
}
}
The output is shown here:
10, 20
88, 99
Like generic classes, generic structures can have constraints. For example,
this version of
XY
restricts type arguments to value types:
struct XY where T : struct {
// ...
Creating a Generic Method
As the preceding examples have shown, methods inside a generic class can make use of a
class’ type parameter and are, therefore, automatically generic relative to the type parameter.
However, it is possible to declare a generic method that uses one or more type parameters
of its own. Furthermore, it is possible to create a generic method that is enclosed within a
non-generic class.
Let’s begin with an example. The following program declares a non-generic class called
ArrayUtils
and a static generic method within that class called
CopyInsert( )
. The
CopyInsert( )
method copies the contents of one array to another, inserting a new element at a specified
location in the process. It can be used with any type of array.
// Demonstrate a generic method.
using System;
// A class of array utilities. Notice that this is not
// a generic class.
class ArrayUtils {
// Copy an array, inserting a new element
// in the process. This is a generic method.
public static bool CopyInsert(T e, uint idx,
T[] src, T[] target) {
// See if target array is big enough.
if(target.Length < src.Length+1)
return false;
www.freepdf-books.com