Generic

When we look at the term “generic”, unrelated to the programming world, it simply means something that is not tied to any sort of brand name

Generic in C#.net

By using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations. Certainly There  are more references and books by which you could visit . please check the given link: Microsoft Visual C# 2005 Step by Step Approach

Use generic types to maximize code reuse, type safety, and performance.

The most common use of generics is to create collection classes.

The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.

You can create your own generic interfaces, classes, methods, events and delegates.

Generic classes may be constrained to enable access to methods on particular data types.

Information on the types used in a generic data type may be obtained at run-time by means of reflection.

 

Creating Our First Generic Type

public class Genric_Kartik<K>

{

private K k;

public K Kartik

{

get

{ return k; }

set

{k = value; }

}

}

And on button click I call my generic type, so it depends on you like where you want to assign a value for Ur generic type

 

protected void Button1_Click(object sender, EventArgs e)

{

Genric_Kartik<string> str = new Genric_Kartik<string>();

Genric_Kartik<int> str1 = new Genric_Kartik<int>();

str.Kartik = “HI REW”;

str1.Kartik = 23423;

Response.Write(str.Kartik);

Response.Write(str1.Kartik);

}

Generic Collections

Collection of a Type that we create, which we used to represent a GenricCollection in our system. Here is the definition for that class:

 

public class GenricCollection

{

protected string Myname;

protected int Myage;

public string MyName { get { return Myname; } set { Myname = value; } }

public int MyAge { get { return Myage; } set { Myage = value; } }

}

protected void Button1_Click(object sender, EventArgs e)

{

System.Collections.Generic.List<GenricCollection> Kartik = new System.Collections.Generic.List<GenricCollection>();

for (int x = 0; x < 5; x++)

{

GenricCollection GC = new GenricCollection();

GC.MyName = “The Sign OF Success !!”;

GC.MyAge = x;

Kartik.Add(GC);

Response.Write(GC.MyName);

Response.Write(GC.MyAge);

}

}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.