Check if property has attribute
There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):
var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));
If you need to retrieve attribute properties then
var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
// Use attr[0], you'll need foreach on attr if MultiUse is true
}
Check if a property has a specific attribute?
You can try the following code the check against an attribute value of a property:
public bool CheckPropertyAttribute(Type type, string property,
Type attributeType, string attProp, object value)
{
var prop = type.GetProperty(property);
if (prop == null) return false;
return CheckPropertyAttribute(prop, attributeType, attProp, value);
}
public bool CheckPropertyAttribute(PropertyInfo prop, Type attributeType,
string attProp, object value){
var att = prop.GetCustomAttributes(attributeType, true);
if (att == null||!att.Any()) return false;
var attProperty = attributeType.GetProperty(attProp);
if (attProperty == null) return false;
return object.Equals(attProperty.GetValue(att[0], null),value);
}
Usage::
if(CheckPropertyAttribute(pi, typeof(DisplayAttribute), "AutoGenerateField", false)){
//...
}
NOTE: I provided 2 overloads, but in your case I think you just need to use the second overload (the case in which we already have some PropertyInfo
).
Check if a property has a DisplayNameAttribute
var t = typeof(SampleDTO);
var pi = t.GetProperty("PropertyA");
var hasAttr = Attribute.IsDefined(pi, typeof(DisplayName));
How to check if an object has an attribute?
Try hasattr()
:
if hasattr(a, 'property'):
a.property
See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!
The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr
. If the property is likely to not be there most of the time, or you're not sure, using hasattr
will probably be faster than repeatedly falling into an exception block.
check if PropertyDescriptor has attribute
You could use LINQ. A chain of the .OfType<T>()
and .Any()
extension methods would do the job just fine:
PropertyDescriptor targetProp = targetProps[i];
bool hasDataMember = targetProp.Attributes.OfType<DataMemberAttribute>().Any();
Check if property has an specified attribute, and then print value of it
Console.WriteLine(property.GetValue(customer).ToString());
However, this will be pretty slow. You can improve that with GetGetMethod
and creating a delegate for each property. Or compile an expression tree with a property access expression into a delegate.
Check if instance of class is annotated with attribute
Since what I'm trying to do doesn't seem to be possible exactly, I found a different way to do it, based on the suggestion of @user1578874. I added an IsRequired property to Employment and used MVC Foolproof Validation to mark those properties as [RequiredIf("IsRequired")]. Seems to be the cleanest solution.
How to get a list of properties with a given attribute?
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]()
.
How can reflection be used to determine if an attribute exists on a property?
The following code works:
using System.Web.Script.Serialization;
public class TestAttribute
{
[ScriptIgnore]
public string SomeProperty1 { get; set; }
public string SomeProperty2 { get; set; }
public string SomeProperty3 { get; set; }
[ScriptIgnore]
public string SomeProperty4 { get; set; }
}
Define a static extension:
public static class AttributeExtension
{
public static bool HasAttribute(this PropertyInfo target, Type attribType)
{
var attribs = target.GetCustomAttributes(attribType, false);
return attribs.Length > 0;
}
}
Put the following sample code into a method and it picks up the attribute correctly - including ICollection
by the way:
var test = new TestAttribute();
var props = (typeof (TestAttribute)).GetProperties();
foreach (var p in props)
{
if (p.HasAttribute(typeof(ScriptIgnoreAttribute)))
{
Console.WriteLine("{0} : {1}", p.Name, attribs[0].ToString());
}
}
Console.ReadLine();
NOTE: if you're using EF dynamic proxy classes, I think you will need to use ObjectContext.GetObjectType()
to resolve to the original class before you can get the attributes, since the EF-generated proxy class will not inherit the attributes.
Related Topics
Htmlagilitypack -- Does <Form> Close Itself for Some Reason
Casting List<T> - Covariance/Contravariance Problem
How to Get the Line Number Which Threw Exception
How to Get the Directory from a File's Full Path
How to Correctly Prefix a Word with "A" and "An"
Adding Stored Procedures Complex Types in Entity Framework
How to Get Urls of Open Pages from Chrome and Firefox
Fluent API, Many-To-Many in Entity Framework Core
Query Microsoft Access Mdb Database Using Linq and C#
Put Wpf Control into a Windows Forms Form
How to Read Regex Captures in C#
Create SQLite Database and Table
How to Return a Specific Status Code and No Contents from Controller
C# Entity-Framework: How to Combine a .Find and .Include on a Model Object
Populate Treeview with File System Directory Structure