Jasmine
Jasmine

Reputation: 5326

Volatile keyword in C# doesn't give compile time error if it's declared in a local field of a class

volatile XmlDocument d;

Just wondering why it is not a compile time error. I read that, we cannot make a field that is local as volatile. Please help me understand.

Upvotes: 0

Views: 185

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

As per MSDN documentation of volatile keyword -

The volatile keyword can be applied to fields of these types:

  1. Reference types.

  2. Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a "pointer to volatile."

  3. Types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.

  4. An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.

  5. Generic type parameters known to be reference types.

  6. IntPtr and UIntPtr.

The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declared volatile.

As stated local variables in method cannot be marked volatile but its perfectly legal to have volatile class field.

Upvotes: 2

Related Questions