create a class in class file:
public class Col<T>
{
T t;
public T Val { get { return t; } set { t = value; } }
}
in the front end create an instance of this class
/create a string version of our generic class
Col<string> mystring = new Col<string>();
//set the value
mystring.Val = “hello”;
//output that value
Response.Write(mystring.Val);
//output the value’s type
Response.Write(mystring.Val.GetType());
//create another instance of our generic class, using a different type
Col<int> myint = new Col<int>();
//load the value
myint.Val = 5;
//output the value
Response.Write(myint.Val);
//output the value’s type
Response.Write(myint.Val.GetType());
example 2:
Using the code
I tried with our simple address book example in this article. Address class contains properties of DoorNo (int), StreetName (string), CityName (string), and PhoneNumber (int). In my implementation part, I may use all this properties to the object or some may be missed out:
class Address
{
int _DoorNo;
public int DoorNo
{
get { return _DoorNo; }
set { _DoorNo = value; }
}
string _StreetName;
public string StreetName
{
get { return _StreetName; }
set { _StreetName = value; }
}
string _City;
public string City
{
get { return _City; }
set { _City = value; }
}
string _State;
public string State
{
get { return _State; }
set { _State = value; }
}
int _Phone;
public int PhoneNo
{
get { return _Phone; }
set { _Phone = value; }
}
public Address() { }
public Address(int DoorNumber, string StreetName, string CityName)
{
this.DoorNo = DoorNumber;
this.StreetName = StreetName;
this.City = CityName;
this.PhoneNo = 0;
}
public Address(int DoorNumber, string StreetName, string CityName, int PhoneNumber)
{
this.DoorNo = DoorNumber;
this.StreetName = StreetName;
this.City = CityName;
this.PhoneNo = PhoneNumber;
}
}
// Main class as follows:
class Program
{
static void Main(string[] args)
{
List<Address> myAddress = new List<Address>();
myAddress.Add(new Address(1,"New Street", "Chennai"));
myAddress.Add(new Address(2, "Second Main Road, TNHB", "Chennai", 866413553));
myAddress.Add(new Address(3, "New Street", "Bangalore"));
myAddress.Add(new Address(4, "Second Main Road, TNHB", "Bangalore", 885634367));
myAddress.Add(new Address(5, "New Street", "Pune"));
myAddress.Add(new Address(6, "Second Main Road, TNHB", "Pune", 433243664));
myAddress.Add(new Address(7, "New Street", "Gurgaon"));
myAddress.Add(new Address(8, "Second Main Road, TNHB", "Gurgaon", 564778634));
foreach (Address a in myAddress)
{
Console.WriteLine("New Address Entry follows: \n");
Console.WriteLine("Door Number : " + a.DoorNo);
Console.WriteLine("Street Name :" + a.StreetName);
Console.WriteLine("City :" + a.City);
Console.WriteLine("Phone Number:" + a.PhoneNo+"\n\n");
}
Console.ReadLine();
}
}
ref:http://www.codeproject.com/KB/cs/Generics_in_C__20.aspx