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
Is there any way to get the method parameter values dynamically using reflection ?
Posted by: Robin | September 02, 2009 at 11:46 PM
Lady Gaga is probably my biggest guilty pleasure in music. I can't explain why I like her.
And you?
Posted by: Alice | February 18, 2010 at 03:33 AM
Zulfiqar, I am sorry to see the difference of the Title of this post and the PropertyInfo thing coming out. Do you really think PropertyInfo is a PARAM? I strongly disagree. Please do change the tile as "C# Reflection, Accessing/reading properties dynamically" or like this.
Thanks
Posted by: Asif Ashraf | February 26, 2010 at 01:05 AM
You sound like giving us a tutorial for getting ParameterInfo array from a type OR accessing local parameters list inside Method body dynamically just like we can read LocalVariables from MethodBody or MethodBase. Thanks
Posted by: Asif Ashraf | February 26, 2010 at 01:08 AM
Please, do change the web page title. wtf is devleopment?
Posted by: jorge | July 25, 2011 at 07:20 AM
This was great and useful. But now, I need to create a centralized logging mechanism, and there, I'd like to be able to log all parameters using a simple code call:
LogHelper.LogParameters();
Is it also possible?
Posted by: Saeed Neamati | December 29, 2011 at 12:01 AM