简体   繁体   中英

Generating warnings for Int32 to Int64 casts

Is there a way to generate compile time warnings for implicit int to long conversions? (An answer that involves a static analysis tool such as FxCop would be fine.)

Casting an int to a long is obviously a safe operation, but say we have a library that used to have int values for its identifiers and which is now upgraded to use long values for all of them.

Now, the client code needs to be updated accordingly. Because if the client is supplying an Int32 argument to a method that expects Int64 - it is very possible that the client code needs to be updated.

An example scenario would be the following:

private void OnProcessGizmoClick()
{
    int gizmoId = 2;

    // I want the following usage to generate warnings:
    GizmoFactoryInstance.ProcessGizmo(gizmoId);
}

// Library code
public void ProcessGizmo(long gizmoId);

I think that the best way would be to overload the method with an Int32 parameter input, which internally could just perform the cast to Int64 - but your overloaded method could be marked as Deprecated.

[Obsolete("Please use an Int64 for your identifier instead")]

Then Visual Studio will see both versions, and use the Int32 declaration which would give a deprecated warning.

If in a later release, or for certain methods that you absolutely don't want to be called with the Int32 parameter you were to decide that you wanted to cause a compiler error, you could also update it to the following.

[Obsolete("Please use an Int64 for your identifier instead", true)]

Define your own type with implicit conversion from both long and int ; make warning on implicit conversion from int like:

public struct GizmoInteger
{
  private long m_Value;
  private GizmoInteger(long value)
  {
    m_Value = value;
  }

  [Obsolete("Use long instead")]
  public static implicit operator GizmoInteger(int value)
  {
    return new GizmoInteger(value);
  }

  public static implicit operator GizmoInteger(long value)
  {
    return new GizmoInteger(value);
  }
}

void Foo(GizmoInteger i)
{
}

// warning
Foo(4);
// OK
Foo(4L);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM