Generics type example in C# | Generic Class | Generic Method | C# Bangla Tutorial | Advanced C#

 

What is Generics?


1. Generics (in  the "System.Collections.Generic" namespace) were introduced in the 2.0 version of .Net and are now widely used. 
2. Generics allow you to write a class or method that can work with any data type.
3. It allows you to define a class with placeholders for the type of its fields, methods, parameters, etc. 
4. Generics replace these placeholders with some specific type at compile time.

When to use Generics?

1. When you use various data types, you need to create a generic type. 
2. It is easier to write code once and reuse it for multiple types.
3. If you are working on a value type then for that boxing and unboxing operation will occur, Generics will eliminate the boxing and unboxing operations. 

Important Points

1. Generics denotes with angel bracket <>. 
2. Compiler applys specified type for generics at compile time. 
3. Generics can be applied to interface, abstract class, method, static method, property, event, delegate and operator.
4. Generics performs faster by not doing boxing & unboxing.

Advantages

1. Increases the reusability of the code.
2. Code is not duplicated for multiple types of data.
3. Generic are type safe. You get compile time errors if you try to use a different type of data than the one specified in the definition. 
4. Generic has a performance advantage because it removes the possibilities of boxing and unboxing.
5. You can create your own generic interface, classes, method, events and delegate.

Post a Comment

Previous Post Next Post