Generic Type Safe Data

Generics are the most powerful feature introduced with C# 2.0. Generics allows the developer to define type-safe data structures, without committing to actual data types. Therefore, a considerable flexibility can be apprehended while using this feature.

In this example we showing how to use type safe data type, without committing data type at the server end,  while client shows the flexibility in changing data type.

A sample code from Microsoft

Step: 1 Create website. (http://manas6/aspnet.35/mm.GenericsTypeSafe1/)

Add a class

Step: 2 Add codes

Class1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//for Stack
using System.Collections;

/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1<T>
{
T[] myType;
Stack myStack = new Stack();
int StackPointer = 0;
string strPrint;
public Class1()
{
//
// TODO: Add constructor logic here
// limitong stack to 10
myType = new T[10];
}
// Note we did not commit to any data type
public void Push(T x)
{
myType[StackPointer++] = x;
}

//
public string Print()
{
for (int i = StackPointer - 1; i >= 0; i--)
{
strPrint += String.Format(" Value: {0}{1}{2}", myType[i], ", Data Type: ", myType[i].GetType());
strPrint += "<br/>";
}
return strPrint;
}

}

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>mm.GenericsTypeSafe1: </title>
</head>
<body bgcolor="#FFFFCC">
<form id="form1" runat="server">
<div>
<asp:Label ID="L1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
 

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Class1<string> strClass1 = new Class1<string>();
Class1<int> intClass1 = new Class1<int>();
intClass1.Push(1);
strClass1.Push("String1");
intClass1.Push(2);
strClass1.Push("String2");
L1.Text += "<font color='red'> String :</font><br/> " + strClass1.Print();
L1.Text += "<font color='green'>Integers :</font><br/> " + intClass1.Print();
}
}
 

 

Step: 3 Runtime View