Skip to content

[Analyzer] Adjust/simplify code for numeric IntPtr #74518

Open

Description

@buyaa-n

Related to #72348

With numeric IntPtr feature code simplification opportunities now available that could be suggested by this analyzer

  • U?IntPtr.Zero ➡ 0 or nu?int.Zero if it would introduce ambiguity
  // Flag:
  IntPtr intPtr = IntPtr.Zero;      // or nint intPtr1 = IntPtr.Zero;
  UIntPtr uintPtr1 = UIntPtr.Zero;  // nuint uintPtr1 = UIntPtr.Zero; 

  // Violations fixed
  nint intPtr1 = 0; // or void* intPtr1 = null; if it needs to be pointer
  nuint uintPtr1 = 0;
  • 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.
  // Flag:
  IntPtr intPtr1 = new IntPtr(x);
  uintPtr1 = new UIntPtr(x);

  // Fixed
  nint intPtr1 = x; 
  uintPtr1 = (nuint)x;
  • x.ToU?Int32() ➡ checked((u?int)x) or (u?int)x if we are in a checked context
  // Flag:
  int i = intPtr1.ToInt32();
  uint ui = uintPtr1.ToUInt32();

  // Fixed
  int i = (int)intPtr1;
  uint ui = (uint)uintPtr1;
  • x.ToU?Int64() ➡ (u?long)x
  // Flag:
  long longValue = intPtr1.ToInt64();
  ulong uLongValue = uintPtr1.ToUInt64();

  // Fixed
  long longValue = (long)intPtr1;
  ulong uLongValue = (ulong)uintPtr1;
  • x.ToPointer() ➡ (void*) x
  // Flag:
  void* ptr1 = intPtr1.ToPointer();
  void* ptr2 = uintPtr1.ToPointer();

  // Fixed
  void* ptr1 = (void*)intPtr1;
  void* ptr2 = (void*)uintPtr1; 

Suggested severity : "Info"
Suggested category : "Style" or "Usage"

This analyzer should be triggered only if the underlying runtime supports numeric IntPtr feature, i.e. if System.Runtime.CompilerServices.RuntimeFeature.NumericIntPtr is available in corelib.

Other related questions:

  • In case the statement includes a variable declaration with U?IntPt, the type also could be converted to nu?int which also could be covered by IDE0049 should be updated to suggest converting IntPtr to nint and UIntPtr to nuint, so these scenarios might also could be added to that issue to fix all references with appropriate values.
  • Also, as @jkotas suggested it would be nice for the code-fixer to suggest replacing IntPtr with actual pointer types where the code is actually operating on pointers. It might be not easy to determine if actual pointer should be suggested instead of nu?int

CC @tannergooding @jeffhandley

Activity

  1. added
    code-analyzer
    code-fixer
    on Aug 24, 2022
  2. ghost added
    untriaged
    on Aug 24, 2022
  3. added this to the Future milestone on Aug 24, 2022
  4. ghost removed
    untriaged
    on Aug 24, 2022
  5. added
    api-ready-for-review
    on Aug 24, 2022
  6. modified the milestones: Future, 8.0.0 on Nov 11, 2022
  7. iSazonov commented on Dec 2, 2022

    @iSazonov
    Contributor

    It would be great to have in .Net 8!

  8. GrabYourPitchforks commented on Dec 6, 2022

    @GrabYourPitchforks
    Member

    We did an unofficial (lacking quorum) review of this. Some notes:

    • Would we prefer to use nint.Zero instead of (nint)0 to avoid ambiguity at call sites where we can't use simply 0?
    • It's common enough for projects to compile debug in checked, release in unchecked. This could complicate the fixer's logic as to whether any given call site is checked or unchecked, since it could be influenced by external factors unknown to the fixer. Might be safest to have it insert an explicit checked(...) statement, regardless of what the fixer believes the current context is.
    • For conversions to void* and [u]long, no need to worry about checked / unchecked context. These conversions are guaranteed lossless so will never fail.
  9. buyaa-n commented on Jan 4, 2023

    @buyaa-n
    ContributorAuthor
    • Would we prefer to use nint.Zero instead of (nint)0 to avoid ambiguity at call sites where we can't use simply 0?

    Sounds good, updated the description accordingly

    • It's common enough for projects to compile debug in checked, release in unchecked. This could complicate the fixer's logic as to whether any given call site is checked or unchecked, since it could be influenced by external factors unknown to the fixer. Might be safest to have it insert an explicit checked(...) statement, regardless of what the fixer believes the current context is.

    The operations coming from roslyn provide Checked property we could use for determining checked/unchecked context , I am not sure that covers the scenario you mentioned, most likely it is. Anyway, instead of trying to check the context and offer an appropriate fixer or always offering explicit checked(...) we could just offer the 2 options both: checked((u?int)x) and (u?int)x, and let the user choose.

    • For conversions to void* and [u]long, no need to worry about checked / unchecked context. These conversions are guaranteed lossless so will never fail.

    Right, updated conversions to [u]long,

  10. bartonjs commented on Feb 28, 2023

    @bartonjs
    Member

    Looks good as proposed. The only representative case that's not explicitly mentioned is var nint = IntPtr.Zero, which needs special handling because of var.

  11. added
    api-approved
    and removed
    api-ready-for-review
    on Feb 28, 2023
  12. modified the milestones: 8.0.0, Future on Aug 11, 2023
  13. added
    help wanted
    on Apr 2, 2024
  14. Manish-1kumar commented on Nov 25, 2026

    @Manish-1kumar
    Contributor

    @buyaa-n @jeffhandley I'd like to implement this analyzer and fixer in dotnet/sdk (Microsoft.CodeAnalysis.NetAnalyzers) if a PR is welcome.

    One scope note: Roslyn's IDE0049 already rewrites the type names IntPtr/UIntPtr to nint/nuint on C# 11 with numeric IntPtr support, so I'd leave type names to IDE0049 and cover the member patterns from the approved list:

    • U?IntPtr.Zero → 0 (or nu?int.Zero where 0 would be ambiguous, including the var case from the review)
    • new U?IntPtr(x)
    • ToU?Int32() / ToU?Int64(), respecting checked/unchecked context
    • ToPointer()

    It would only fire when numeric IntPtr is available. I'd use the suggested severity Info; for category, the description suggests "Style" or "Usage". Which do you prefer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-Metacode-analyzercode-fixerhelp wanted

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions