What is Generic in C# ?

Generic means not specific to particular data type. C# allows you to define generic generic classes, interfaces, abstract classes, properties, events, delegates and operators using the type parameter and without specific data types. A type parameter is a placeholder for a particular type specified when creating an instance of the generic type.

A generic type is declared by specifying a type parameter in angle brackets after type name, e.g TypeName<T> where T is a type parameter.

Below is the example where we are declaring class with generic type. Here KeyValue class will have string type constant for key property and generic type T as for Value property.

Now we will see how can we Instantiate generics in C#.

In the Above example we have instantiated List with Type as KeyValue class which is having type both as string. Then we have added some values into the list by instantiating KeyValue type anonymously. After that we are iterating through kv list and printing the values. Below is the output of the above code.

We can put any type instead of generic type while instantiating which makes it more reusable.

Thank you for reading please comment your suggestions, share the article, follow me and Abhima C# Programming publication.

Bhagavad Gita Verse of the Day

अव्यक्ताद्व्यक्तय: सर्वा: प्रभवन्त्यहरागमे |
रात्र्यागमे प्रलीयन्ते तत्रैवाव्यक्तसञ्ज्ञके || 18||

avyaktād vyaktayaḥ sarvāḥ prabhavantyahar-āgame
rātryāgame pralīyante tatraivāvyakta-sanjñake

BG 8.18: At the advent of Brahma’s day, all living beings emanate from the unmanifest source. And at the fall of his night, all embodied beings again merge into their unmanifest source.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vishal Pathak

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud