Generic Classes
Generic classes use reference semantics, supporting mutable state and object identity. Type parameters are declared in angle brackets after the class name, and then used in fields, method parameters, and return types. Generic classes are suitable for implementing data structures that need to encapsulate state, such as containers, stacks, queues, etc.
Stack<T> is a classic example of a generic class. One implementation can handle any element type: Stack<Int64>, Stack<String>, or Stack< Pair<Int64, String> >. The type parameter T appears in field initialization expressions, method parameter types, and return types, ensuring type safety.
Static members of generic classes cannot reference type parameters. Because static members share memory, if static members could reference T, then static members of Stack<Int64> and Stack<String> would have different types, which contradicts the semantics of shared memory.
Stack<Int64> and Stack<String> are incompatible with each other.Run the example code, observe the push and pop operations on the stack, then modify the code to create a stack that stores strings.