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.
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"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With