You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class
DataStore
.
DataStore<string> store = new DataStore<string>();
Above, we specified the string
type in the angle brackets while creating an instance. So,
T
will be replaced with a string
type wherever T
is used in the entire class at compile-time. Therefore, the type of
Data
property would be a string
.
You can assign a string value to the Data
property. Trying to assign values other than string will result in a compile-time error.
DataStore<string> store = new DataStore<string>();
store.Data = 'Hello World!';
//store.Data = 123; //compile-time error
You can specify the different data types for different objects, as shown below.
DataStore<string> strStore = new DataStore<string>();
strStore.Data = 'Hello World!';
//strStore.Data = 123; // compile-time error
DataStore<int> intStore = new DataStore<int>();
intStore.Data = 100;
//intStore.Data = 'Hello World!'; // compile-time error
KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>();
kvp1.Key = 100;
kvp1.Value = 'Hundred';
KeyValuePair<string, string> kvp2 = new KeyValuePair<string, string>();
kvp2.Key = 'IT';
kvp2.Value = 'Information Technology';