I have seen this question come up over and over again on how to build parameter list automatically for a given object. An obvious application is enumerating through all the properties and building up list of parameters before saving an object to the database.
How would you do it?
Simple way to do it would be to hand code each parameter name, its type, and value.
Another way would be to use reflection. Here is a sample code on how to achieve it in a very simple manner.
Here are the relevant name spaces
using System;
using System.Reflection;
A sample class:
public class Employee
{
private string fname;
private string lname;
private int salary;
public Employee(){}
public Employee(string fname,string lname,int salary)
{
this.fname = fname;
this.lname = lname;
this.salary = salary;
}
public string FirstName
{
get {return this.fname;}
set {this.fname = value;}
}
public string LastName
{
get {return this.lname;}
set {this.lname = value;}
}
public int Salary
{
get {return this.salary;}
set {this.salary = value;}
}
}
And the test code to create the parameter list
Employee e = new Employee("zulfiqar","syed",33);
foreach(PropertyInfo pinfo in typeof(Employee).GetProperties())
{
Console.WriteLine("Propety Name: {0} Type = {1} Value = {2}",
pinfo.Name,
pinfo.PropertyType,
pinfo.GetValue(e,new Object[] {})
);
}
Console.WriteLine("all done");
Console.ReadLine();
Once you execute the code, the output would look as follows:
Propety Name: FirstName Type = System.String Value = zulfiqar
Propety Name: LastName Type = System.String Value = syed
Propety Name: Salary Type = System.Int32 Value = 33
all done
hth..
Happy coding..
ZULFIQAR SYED
Recent Comments