GENERIC TYPE
PUBLISHED 10/03/2023
Last updated
PUBLISHED 10/03/2023
Last updated
Generic in C# means not specific to a particular data type.
C# allows programmers to define generic class, interfaces, abstract classes, fields, methods, static methods, properties, delegates, events, and operators using the Type Parameter and without the specific data type
TYPE PARAMETER --> a placeholder for a particular type specified when creating an instance of the generic type --> Declared by specifying a type parameter in angled brackets after a type name
TypeName<T>
--> Where T is a type parameter
Increase the reusability of the code --> Do not need to rewrite code to handle different data types
Generics are type-safe --> program will throw compile-time errors if you try to use a different data type than the one specified in the definition
Generics has a performance advantage because it removes the possibilities of boxing and unboxing
Generic classes are defined using a type parameter in an angled bracket after the class name
DataStore
is a generic class
T
is the Type Parameter
Can be used as a type of field, property, method parameter, return type, or delegates in the DataStore Class
You can also define multiple type parameters separated by a comma
A generic class increases the reusability -->the more type parameters used, the more reusable the code becomes --> too much generalization makes code difficult to understand and maintain
A generic class can be a base class to other generic or non-generic classes or abstract classes
A generic class can be derived from other generic or non-generic interfaces, classes, or abstract classes
A program can create an instance of generic classes by specifying an actual data type in angle brackets
The above line of code creates an instance of the generic class DataStore. It specifies the string type in angle brackets while creating the instance... --> T will be replaced with a string type wherever T is used in the entire class @ compile-time --> The type of Data property would be string
A generic class can include generic fields, which CANNOT be initialized
A method declared with the type parameters for its return type or parameters is called a generic method
The AddOrUpdate() and the GetData() methods are generic methods
--> The actual data type of the item parameter will be specified at the time of instantiating the DataStore<T> class