Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions docs/csharp/misc/cs0677.md
Comment thread
BillWagner marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ ms.assetid: 6a4a3703-9b44-4c4f-a564-8b437b1cb6b8

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

- Any reference type
- Any reference type.

- Any pointer type (in an `unsafe` context)
- Any pointer type (in an `unsafe` context).

- The types `sbyte`, **byte**, **short**, `ushort`, `int`, `uint`, `char`, **float**, `bool`
- The types `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `char`, `float`, `bool`.

- Enum types based on any of the above types
- Enum types based on any of the listed types.

The following sample generates CS0677:

Expand All @@ -35,3 +35,28 @@ class TestClass
}
}
```

## 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:

```csharp
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](../language-reference/builtin-types/integral-numeric-types.md#native-sized-integers).

As general guidance on thread-safe programming, consider using <xref:System.Threading.Interlocked> operations or the [`lock`](../language-reference/statements/lock.md) statement instead of `volatile` fields.