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.
If you wanted to check for non-instance properties, private properties, or other options, you can tweak the
BindingFlagsvalues in that statement. Your usage syntax wouldn’t be exactly what you give. Instead: