Tom Gullen Tom Gullen - 1 month ago 8
C# Question

Does object have attribute

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
?

Answer

The simplest way is to use following code:

public static void Set(object objectToCache)
{
    Console.WriteLine(objectToCache.GetType().IsDefined(typeof(MyAttribute), true));
}