Pointers should not be visible
TypeName |
PointersShouldNotBeVisible |
CheckId |
CA2111 |
Category |
Microsoft.Security |
Breaking Change |
Breaking |
Cause
A public or protected System.IntPtr or System.UIntPtr field is not read-only.
Rule Description
IntPtr and UIntPtr are pointer types used to access unmanaged memory. If a pointer is not private, internal, or read-only, malicious code can change the value of the pointer, potentially allowing access to arbitrary locations in memory or causing application or system failures.
If you intend to secure access to the type that contains the pointer field, see Secured types should not expose fields.
How to Fix Violations
Secure the pointer by making it read-only, internal, or private.
When to Exclude Warnings
Exclude a warning from this rule if you do not rely on the value of the pointer.
Example
The following code shows pointers that violate and satisfy the rule. Note that the non-private pointers also violate the rule Do not declare visible instance fields.
using System;
namespace SecurityRulesLibrary
{
public class ExposedPointers
{
// Violates rule: PointersShouldNotBeVisible.
public IntPtr publicPointer1;
public UIntPtr publicPointer2;
protected IntPtr protectedPointer;
// Satisfies the rule.
internal UIntPtr internalPointer;
private UIntPtr privatePointer;
public readonly UIntPtr publicReadOnlyPointer;
protected readonly IntPtr protectedReadOnlyPointer;
}
}
Related Rules
Secured types should not expose fields
Do not declare visible instance fields