Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what is the best way to find out if a class has a property (using reflection)

Tags:

c#

reflection

I have a class

 public class Car
 {
       public string Name {get;set;}
       public int Year {get;set;}
 }

In seperate code, i have a field name as as string (let use "Year") as an example.

I want to do something like this

   if (Car.HasProperty("Year")) 

which would figure out if there is a Year field on the car object. This would return true.

   if (Car.HasProperty("Model"))

would return false.

I see code to loop through properties but wanted to see if there was a more succinct way to determine if a single field exists.

like image 503
leora Avatar asked Feb 06 '12 12:02

leora


2 Answers

This extension method should do it.

static public bool HasProperty(this Type type, string name)
{
    return type
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Any(p => p.Name == name);
}

If you wanted to check for non-instance properties, private properties, or other options, you can tweak the BindingFlags values in that statement. Your usage syntax wouldn't be exactly what you give. Instead:

if (typeof(Car).HasProperty("Year"))
like image 57
David M Avatar answered Oct 19 '22 16:10

David M


Since you seem to be looking only for public properties, Type.GetProperty() can do the job:

if (typeof(Car).GetProperty("Year") != null) {
    // The 'Car' type exposes a public 'Year' property.
}

If you want to further abstract the code above, you can write an extension method on the Type class:

public static bool HasPublicProperty(this Type type, string name)
{
    return type.GetProperty(name) != null;
}

Then use it like this:

if (typeof(Car).HasPublicProperty("Year")) {
    // The 'Car' type exposes a public 'Year' property.
}

If you also want to check for the presence of non-public properties, you will have to call the override of Type.GetProperties() that takes a BindingFlags argument, and filter the results as David M does in his answer.

like image 36
Frédéric Hamidi Avatar answered Oct 19 '22 17:10

Frédéric Hamidi