Generics in C#

Cool. Hey everyone this is my first post on my blog. Today i am going to explain a bit about the generics and its use.So, lets start with the introduction to it.

Introduction

Generics are the cool features introduce in C# 2.0. Generics allows programmer to design classes and methods decoupled from the data types. It means generics helps the programmer to make their classes and methods type independent.

Generics are extensible used by the collection classes available in  System.Collection.Generics namespace.

Features of using Generics

  • It allows the programmer to maximize  code reuse, type safety and performance.
  • Programmers can create their own generics methods,classes,interfaces and delegates.
  • .Net Framework class library contains the bunch of generics classes in the System.Collection.Generics namespace. For example programmer can use List,Dictionary etc. in their code.

Generics Classes

Lets take a quick example for making a class generics. In this post i will only discuss about making a class generics.I will be doing other in later post.

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Product<string, int> watch = new Product<string, int>("Fastrack", 2000);
Console.WriteLine(watch.ToString());
Console.ReadKey();
}
}
class Product<TName , TPrice>
{
public TName name;
public TPrice price;

public Product(TName _name , TPrice _price)
{
name = _name;
price = _price;

}

public override string ToString()
{
return name + "," + price;
}
}

}

Output

Screenshot (3)

 

 

 

 

 

 

 

 

This is how generics works in C#. Thanks for reading my post.

Keep Coding

😀

Leave a comment