Search code examples
c#reflectionvolatile

Figure out if reflected field is volatile


I'm trying to mine information from an assembly using reflection, and one of the things I'd like to know (give that it is actually a thing to know) is if a field is volatile or not. In other words, if I have the following class

public class Test {
    public volatile int Counter = 0;
}

is there any way I can (with reflection) figure out that the Test.Counter field is indeed volatile? Or is that simply not exported at all?


Solution

  • You could use the GetRequiredCustomModifiers method:

    var field = typeof(Test).GetField("Counter");
    bool isVolatile = field
        .GetRequiredCustomModifiers()
        .Any(x => x == typeof(IsVolatile));