What are Generics in C#?

Generics (Added to version 2.0 of the C# language) introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

Using generics greatly maximizes code reuse, type safety, and performance. The most common use of generics is to create collection classes.




Explanation:

The GenerictList class literally says "I am a collection of whatever you want, and with an instance of me, you can only do one thing: Add"


TestGenericList is a normal class with a sub-class ExampleClass and a method Main(). Watch the lines declaring the list of int, string and ExampleClass and notice that GenericList is instantiated with "Whatever" TestGenericList wants.

That's the power of Generics!!!

The above example shows a Generic Class, but you can also create Generic Methods, generic interfaces, events and delegates.




References:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

Comments

Popular posts from this blog

Why can't Microsoft install IIS on Window Operating Systems by default?

Exam 70-487: Accessing Data - How to choose the Appropriate Data Access Technology - Entity Framework?

Exam 70-487: Accessing Data - How to choose the Appropriate Data Access Technology - Azure Cosmos DB?