Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Advertisements

Generics

Overview

Generics in C# allow for the creation of reusable classes, structures, methods, delegates, and interfaces with placeholder types.

Key Points

  • Reusability: Generics provide reusability through a “template” that contains “placeholder” types.
  • Covariance: Generic types are not covariant. This means that even if type B can be cast to type A, T<B> cannot be cast to T<A>.
  • Constraints: There are three kinds of constraints in generics – derivation constraint, constructor constraint, and reference/value constraint.
  • Derivation Constraint: In the derivation constraint, the base constrained type must never have lower visibility than the generic type parameter.
  • Constraint Order: The order of constraints is important and should be followed as follows:
    1. Reference/Value Constraint
    2. Derivation Constraint
    3. Constructor Constraint

Example


            public class Example<T>
            {
                public T Value { get; set; }

                public Example(T value)
                {
                    Value = value;
                }
            }
        

Conclusion

Understanding generics in C# is crucial for creating flexible and reusable code. By leveraging generics, developers can write more efficient and maintainable code that can work with a variety of data types.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x