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

I have a class

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

In a separate code, I have the field name as a string (let it use "Year") as an example.

I want to do something like this

   if (Car.HasProperty("Year")) 

which will determine if there is a Year field on the vehicle object. This will return true.

   if (Car.HasProperty("Model"))

will return false.

I see code to scroll through properties, but would like to see if there is a more concise way to determine if one field exists.

+5
source share
2 answers

This extension method should do this.

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

-, , BindingFlags . , . :

if (typeof(Car).HasProperty("Year"))
+15

, , public, Type.GetProperty() :

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

, Type class:

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

:

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

public, Type.GetProperties(), BindingFlags , .

+8
source

All Articles