Professional Documents
Culture Documents
C# Generics DJ
C# Generics DJ
C# Generics DJ
First of all, let's take an example where generics can be of great help.
1.
2.
3.
1.
2.
Suppose you are writing a class for Stack with methods Push() and Pop(). You have to implement this
class in such a way that it works for any data type. Now you will have two options if generic was not there to
help you.
Define classes for each data types. You can achieve the solution using this approach. However there
are many disadvantages of this approach:
You are writing redundant code.
If you need to support a new data type, then you need to add a new class for that.
You are discouraging code reusability.
Defined class for data type as object. This is somewhat better than the first approach. However, it
has its own disadvantages.
Performance would be degraded because of boxing and un-boxing.
TypeSafety is lost. Your solution will not be type safe.
Generic solves all the above problems. It:
allows you to define type-safe data structures, without providing actual data types.
allows you to write a class or method that can work with any data type.
Generic Constraints
As you know, you can use any data type with generic classes. Like you can use
data
types with generic Stack class. However, sometimes we need to restrict the data types which can be used
with particular generic class or methods. We can achieve this using generic constraints.
N. While instantiating
object of data type Node, you want to instantiate the object of data type N inside Node class. In this
Suppose you have a generic class
Node
struct
constraint:
Hide Copy Code
Generic Methods
Hide Copy Code