Home > Software engineering >  System.Math.Round call works in one class, but is ambigous in the other
System.Math.Round call works in one class, but is ambigous in the other

Time:08-01

Is this some bug in VS2022 or I'm missed something?

There is no problem with RoundPoint method this code:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Shapes;

namespace Editor.View.Controls
{
    public partial class Workspace : UserControl
    {
        public Workspace() => InitializeComponent();

        // ... some other methods

        public Point RoundPoint(Point p, int r)
        {
             return new Point(Math.Round(p.X / r) * r, Math.Round(p.Y / r) * r);
        }
    }
}

But when I move RoundPoint method to the other class (which is static or not, it doesn't matter):

using System;
using System.Drawing;

namespace Editor.View.Controls
{
    public static class UiHelpers
    {
        public static Point RoundPoint(Point p, int r)
        {
            return new Point(Math.Round(p.X / r) * r, Math.Round(p.Y / r) * r);
        }
    }

    // ...
}

It throws this error:

Error CS0121 The call is ambiguous between the following methods or properties: 'Math.Round(decimal)' and 'Math.Round(double)' Editor\View\Controls\UiHelpers.cs

CodePudding user response:

Your second code file has a using System.Drawing, which means that Point refers to System.Drawing.Point. This uses int not double, so it doesn't make sense to round it (don't forget there is integer division, which means the result of the division is still an int).

Either cast one side of the division to double or decimal, or use System.Drawing.PointF.

Or perhaps you are just using the wrong library altogether, as noted in @Kamil's answer.

CodePudding user response:

I'm answering my own question.

So I just realized that I was using two diffrent Point structs in .NET.

One is here:

System.Windows.Point

and the other is

System.Drawing.Point
  •  Tags:  
  • c#
  • Related