C# Generics Programming

In this chapter you will learn

  • What are Generics
  • How to Write Generics Program in C#
  • Benefit of Generics in C#

What are Generics

In simple words, Generics are the that type of classes which has PalceHolder instead of datatypes. When you create generic classes you don’t specify its data type; datatypes are defined when you create objects. This makes Generic classes reusable and type-safe and your Generic classes and methods are able work with any datatypes.

More about Generics

  1. Generics improves code usability, type safety and performance.
  2. Mostly Generics are used for creating collection classes.
  3. You can use Generics by adding System.Collections.Generic namespace.
  4. You can create your own Generic interfaces, classes, methods, events and delegates.

Declare Generics Class

Use Generics in Programming

Programming Example

Output

Printing Integer Value
144
Printing String Value
Hello String
_

Here, I have wrote the very simple program and hope you will understand it very easily. In the above program I have created a Generic class GenClass which has a placeholder. This class also has a method GetFunction that accepts a T type parameter and prints on the console. is a placeholder that is replaced by datatype when created objects.

Summary

In this chapter you learned What are Generics in C# Programming, Its benefit and complete programming exmaple.


Leave a Reply

Your email address will not be published. Required fields are marked *