Hybridzz Hybridzz - 9 months ago 56
C# Question

Why Attribute.IsDefined not checking my custom attribute list of Myproperty

The below line of code is supposed to give me the list of properties with my attribute defined on it, but it is not giving me any results.

var props = typeof(D).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(MYAttribute)));


sample property

[Serializable]
[Table()]
public class MYClass : IMyInterface
{
[Column()]
[MyAttribute(HeaderFields.MyValue)]
public string MyProp { get; set; }
}


When i debug i am able to see the property contains the attribute in the custom attribute list. What am i missing here?

enter image description here

EDIT

I am trying to get the properties in the below function

private static void MyFunction<D>(D MyObj)
where D : IMyInterface
{
var props = typeof(D).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(MYAttribute)));
}


EDIT

The real issue was Visual studio not giving any conflict error/warning when there is same attribute defined in different namespace.

Answer Source

Assuming you had arranged the following code:

[Serializable]
[Table("FooTable")]
public class MYClass : IMyInterface
{
    [Column("FooColumn")]
    [My(HeaderFields.MyValue)]
    public string MyProp { get; set; }
}

public class MyAttribute : Attribute
{
    public MyAttribute(object myValue) { }
}

public enum HeaderFields
{
    MyValue,
    MyAnotherValue
}

public interface IMyInterface
{
    string MyProp { get; set; }
}

You can now get all of your properties that have defined the attribute MyAttribute, in the following way:

using System;
using System.Linq;
using System.Reflection;

class Program
{
    public static void Main(string[] args)
    {
        var props = typeof(MYClass).GetProperties().Where(prop => prop.IsDefined(typeof(MyAttribute), false));

        foreach (PropertyInfo propertyInfo in props)
        {
            string newLine = Environment.NewLine;

            Console.Out.WriteLine($"propertyInfo:" + newLine +
                                  $"\tName = {propertyInfo.Name}," + newLine +
                                  $"\Format = {propertyInfo}" + newLine);
        }
    }
}

Given the provided example, you should obtain such an outcome:

propertyInfo:

Name = MyProp,

Format = System.String MyProp

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download