Reflection on Class Properties

  • Thread starter Thread starter Brian Pelton
  • Start date Start date
B

Brian Pelton

I want to use reflection to do some special logic on properties of a
specific type (or those that inherit from that type)

Below is an example of what I would like to do. However, I get a
complier error saying that the property will never be of the provided
type. I don't understand.

How can I do this???

Thanks for any help,
Brian




using System;
using System.Reflection;

namespace ReflectSandbox
{

class Employee
{
public FullName EmployeeName;
public string Address;
public string PhoneNumber;
}

class Name
{
public string FirstName;
public string LastName;
}

class FullName : Name
{
public string MiddleName;
}

class Program
{
static void Main(string[] args)
{

Employee a = new Employee();
a.EmployeeName.FirstName = "John";
a.EmployeeName.MiddleName = "Jacob";
a.EmployeeName.LastName = "Smith";
a.Address = "101 N Anywhere";
a.PhoneNumber = "1-800-HELP-ME";

foreach (PropertyInfo p in a.GetType().GetProperties())
{
if (p.PropertyType is Name) //Given Expression is never
//of the provided type
{
//here, do special logic
//for properties of Name type
//or any type that inherits from
//name (i.e. FullName)
}
}
}
}
}
 
I think this works:


foreach (FieldInfo f in a.GetType().GetFields())
{
Console.WriteLine(f.FieldType.FullName);

if (f.FieldType.IsSubclassOf(typeof(Name)))
{
Console.WriteLine("This is of Name type");
}
}
 
You've got the right solution because your classes you are reflecting
derive from each other. If you directly know the class you are
reflecting you could use the following code also:

class Name { ... }

PropertyInfo pI = ....GetType().GetProperties(BindingFlags.Public |
BindingFlags.Instance);

if (pI.PropertyType == typeof(Name))
{
// place code here
}

Matthias
 
This is where you made the mistake:
if (p.PropertyType is Name)
It should be
if (p.GetValue(...) is Name)
or
if (p.PropertyType == typeof(Name))
 
Back
Top