Information Technology Reference
In-Depth Information
Generic Structs
Like generic classes, generic structs can have type parameters and constraints. The rules and
conditions for generic structs are the same as those for generic classes.
For example, the following code declares a generic struct called PieceOfData , which stores
and retrieves a piece of data, the type of which is determined when the type is constructed.
Main creates objects of two constructed types—one using int and the other using string .
struct PieceOfData<T> // Generic struct
{
public PieceOfData(T value) { _Data = value; }
private T _Data;
public T Data
{
get { return _Data; }
set { _Data = value; }
}
}
class Program
{
static void Main() Constructed type
{
PieceOfData<int> IntData = new PieceOfData<int>(10);
PieceOfData<string> StringData = new PieceOfData<string>( "Hi there.");
Constructed type
Console.WriteLine("IntData = {0}", IntData.Data);
Console.WriteLine("StringData = {0}", StringData.Data);
}
}
This code produces the following output:
IntData = 10
StringData = Hi there.
Search WWH ::




Custom Search