volatile Home
This page is specific to:.NET Framework Version:1.12.03.03.54.0
C# Programmer's Reference
volatile

The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

volatile declaration

where:

declaration
The declaration of a field.

Remarks

The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

The type of a field marked as volatile is restricted to the following types:

  • Any reference type.
  • Any pointer type (in an unsafe context).
  • The types sbyte, byte, short, ushort, int, uint, char, float, bool.
  • An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

For more information on volatile, see 10.4.3 Volatile fields.

Example

The following sample shows how to declare a public field variable as volatile.

// csharp_volatile.cs
class Test
{
   public volatile int i;
   
   Test(int _i)
   {
      i = _i;
   }
   public static void Main()
   {
      
   }
}

See Also

C# Keywords | Modifiers | 10.4.3 Volatile fields

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View