Edit

Share via


Compiler Error CS0677

'variable': a volatile field cannot be of the type 'type'

Fields declared with the volatile keyword must be one of the following types:

  • Any reference type.

  • Any pointer type (in an unsafe context).

  • The types sbyte, byte, short, ushort, int, uint, char, float, bool.

  • Enum types based on any of the listed types.

The following sample generates CS0677:

// CS0677.cs  
class TestClass  
{  
   private volatile long i;   // CS0677  
  
   public static void Main()  
   {  
   }  
}  

Potential workarounds

In some scenarios, you might be able to use nint (native-sized integer) instead of long as a workaround for CS0677. The nint type is guaranteed to support atomic access and can be used with the volatile keyword:

class TestClass  
{  
   private volatile nint i;   // This compiles successfully
  
   public static void Main()  
   {  
   }  
}  

The nint type is a native-sized integer that's 32-bit on 32-bit platforms and 64-bit on 64-bit platforms. On 64-bit platforms, nint has the same size and range as long, but it's designed to guarantee atomic access. This workaround is most appropriate when:

  • Your code targets 64-bit platforms where nint provides the same range as long.
  • You need atomic access to a large integer value in a multithreaded context.
  • Platform-specific integer size behavior is acceptable for your use case.

For more information about native-sized integers, see Integral numeric types.

As general guidance on thread-safe programming, consider using Interlocked operations or the lock statement instead of volatile fields.