2

Given the class:

[ProtoContract]
[Serializable]
public class TestClass
{
    [ProtoMember(1)]
    public string SomeValue { get; set; }
}

And the method:

public static void Set(object objectToCache)
{

}

Is it possible to check if objectToCache has the attribute ProtoContract?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

3 Answers3

2

The simplest way is to use following code:

public static void Set(object objectToCache)
{
    Console.WriteLine(objectToCache.GetType().IsDefined(typeof(MyAttribute), true));
}
Alex Aparin
  • 4,393
  • 5
  • 25
  • 51
1

Yes:

var attributes = TestClass.GetType().GetCustomAttributes(typeof(ProtoContract), true);
if(attributes.Length < 1)
    return; //we don't have the attribute
var attribute = attributes[0] as ProtoContract;
if(attribute != null)
{
   //access the attribute as needed
}
Lew
  • 1,248
  • 8
  • 13
1

Use the GetCustomAttributes which will return a collection of attributes the given object has. Then check if any are of your desired type

public static void Main(string[] args)
{
    Set(new TestClass());
}

public static void Set(object objectToCache)
{
    var result = objectToCache.GetType().GetCustomAttributes(false)
                                        .Any(att => att is ProtoContractAttribute);

    // Or other overload:
    var result2 = objectToCache.GetType().GetCustomAttributes(typeof(ProtoContractAttribute), false).Any();
    // result - true   
 }

Reading more about IsDefined as Александр Лысенко suggested it does seem to be what you are looking for:

Returns true if one or more instances of attributeType or any of its derived types is applied to this member; otherwise, false.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95