Here's a practical use of reflection.
Recently in a project I was involved with, I (my application that is) was to receive some XML files generated from another application. My task now was to map these into my own object model and basically it all ended up with the problem with setting an objects property by name.
I.e XML could look like this
<Surname>Peter </Surname>
and I needed to set my objects property called "Surname" to Peter.
To my rescue came reflection. While it's a generic method of retreiving metadata about classes (COM objects as well), it was very simple to apply to my problem. Since I have described my problem and therefore motivated the usage, I have stripped down the example to a very simple (pretty useless in itself) level.
First have a look at the class Customer:
public class Customer
{
private string m_sAdress;
public string Adress
{
get
{
return m_sAdress;
}
set
{
m_sAdress = value;
}
}
private string m_sSurname;
public string Surname
{
get
{
return m_sSurname;
}
set
{
m_sSurname = value;
}
}
private int m_nAge;
public int Age
{
get
{
return m_nAge;
}
set
{
m_nAge = value;
}
}
private string m_sLastname;
public string Lastname
{
get
{
return m_sLastname;
}
set
{
m_sLastname = value;
}
}
public Customer()
{
//
// TODO: Add constructor logic here
//
}
}
Now here's the application:
Customer oCust = new Customer();
oCust.Surname = "John";
oCust.Lastname = "Doe";
oCust.Age = 42;
oCust.Adress = "42 Home Street";
oCust.GetType().GetProperty("Surname").SetValue(oCust,
"Peter",
System.Reflection.BindingFlags.Default,
null,null,null);
oCust.GetType().GetProperty("Age").SetValue(oCust,
24,
System.Reflection.BindingFlags.Default,
null,null,null);
MessageBox.Show(oCust.Surname + ":" + oCust.Age.ToString());
By using GetType() of our .NET object we can receive a PropertyInfo object by name - and that's what we're using to call the property.