How to test for a given Type at runtime

  • Thread starter Thread starter Daniel Billingsley
  • Start date Start date
D

Daniel Billingsley

I know I my coffee must have worn off or something, but how do I test if a
given property of type Type is a particular type. Confused?

For example, let's say I have a System.Reflection.PropertyInfo object and I
want to test its PropertyType property to see if the property (that the
PropertyInfo refers to) is a string type.

I now have
if (testProperty.PropertyType.FullName == "System.String")

but that literal is making my hair stand on end. Is that the way you do it
though?
 
No, that doesn't work because I have the PropertyInfo object not the actual
property. The PropertyType property of the PropertyInfo object is always of
type Type, of course.
 
Ok, but that's still basically the same thing, using a sting literal, which
I hoped I could avoid. Thanks.
 
Daniel said:
Ok, but that's still basically the same thing, using a sting literal, which
I hoped I could avoid. Thanks.

There is no string literal in typeof(string)!
However, try this, if you look for something more "procedural":

if (testProperty.PropertyType == String.GetType())
{
}

bye
Rob
 
Robert Jordan said:
There is no string literal in typeof(string)!
However, try this, if you look for something more "procedural":

if (testProperty.PropertyType == String.GetType())
{
}

There is no string.GetType(). GetType is an instance method, so you *could*
do "".GetType(), but that is a less than attractive way to get strings type,
IMHO.

typeof(string) is the correct way to do this.
 
Back
Top