Skip to content

Analyzer: Adjust code for numeric IntPtr. #72348

@teo-tsirpanis

Description

@teo-tsirpanis

With the advert of the numeric IntPtr feature, nint is an alias for System.IntPtr just like int is an alias for System.Int32. We should add analyzers and fixers to make it clear to user code, especially to those who think that IntPtr represents an opaque pointer-sized value. Here's what the analyzers should do:

  • IDE0049 should be updated to suggest converting IntPtr to nint and UIntPtr to nuint.
  • U?IntPtr.Zero0 or (nu?int)0 if it would introduce ambiguity
  • new U?IntPtr(x)x or (nu?int)x if it would introduce ambiguity, or unchecked((nu?int)x) if we are in a checked context.
  • x.ToU?Int32()checked((u?int)x) or (u?int)x if we are in a checked context
  • x.ToU?Int64()unchecked((u?long)x) or (u?long)x if we are in an unchecked context
  • x.ToPointer()(void*) x
  • Convert explicit casts between U?IntPtr and u?int or u?long, to nu?int, while taking the overflow checking context into account (too many to list).

These analyzers and fixers should be triggered only if the underlying runtime supports numeric IntPtr. Some of them might be legal even without it but it's not necessary to make it more complicated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimecode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions