Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Generic Interface Member is "Pure" (has Pure Attribute)

I have an interface with methods annotated with the Pure attribute from System.Diagnostics.Contracts:

public interface IFoo<T> {
    [Pure]
    T First { get; }

    [Pure]
    T Last { get; }

    [Pure]
    T Choose();

    void Add(T item);

    T Remove();
}

I wish to iterate over the members of the interface and check if the member is pure or not. Currently I'm not able to get any attributes from the member info:

var type = typeof(IFoo<>);
var memberInfos = type.GetMembers();
var memberInfo = memberInfos.First(); // <-- Just select one of them
var attributes = memberInfo.GetCustomAttributesData(); // <-- Empty

What am I missing?

Note that I do not have a class or an instance hereof. Only the interface.

like image 777
Mikkel R. Lund Avatar asked Apr 07 '16 16:04

Mikkel R. Lund


1 Answers

Use a decompiler of your choice and open your assembly. You will see that the PureAttribute will be removed by the compiler. So you can not get it with reflection because is does not exist anymore.

To test you can use another attribute that wont get removed and you will be able to get it using reflection.

Update: On the one hand, as you have mentioned in the comments:

Pure is a conditional attribute ([Conditional("CONTRACTS_FULL")]), and is only added if contracts are enable.

On the other hand your code has a flaw because Linqs First() method will return a member without an attribute, the getter method of the property. You can use code like this to get the expected result: members.Where(x => x.GetCustomAttributes<PureAttribute>().Any()).ToArray().

like image 182
thehennyy Avatar answered Nov 09 '22 20:11

thehennyy