Compare Two Points
One of the functionalities available in the Point
and PointF
classes is the Equals()
method. This method is used to compare two points in terms of their x and y coordinates and returns a boolean value.
Below is a sample code snippet demonstrating the use of the Equals()
method to compare two different points:
using System;
using System.Drawing;
public class PointComparison
{
public static void Main()
{
// Creating two Point objects with specific coordinates
Point point1 = new Point(10, 20);
Point point2 = new Point(10, 20);
// Using the Equals() method to compare point1 with point2
bool arePointsEqual = point1.Equals(point2);
// Output the result of the comparison
Console.WriteLine("Points are equal: " + arePointsEqual);
}
}
using System;
using System.Drawing;
public class PointComparison
{
public static void Main()
{
// Creating two Point objects with specific coordinates
Point point1 = new Point(10, 20);
Point point2 = new Point(10, 20);
// Using the Equals() method to compare point1 with point2
bool arePointsEqual = point1.Equals(point2);
// Output the result of the comparison
Console.WriteLine("Points are equal: " + arePointsEqual);
}
}
Imports System
Imports System.Drawing
Public Class PointComparison
Public Shared Sub Main()
' Creating two Point objects with specific coordinates
Dim point1 As New Point(10, 20)
Dim point2 As New Point(10, 20)
' Using the Equals() method to compare point1 with point2
Dim arePointsEqual As Boolean = point1.Equals(point2)
' Output the result of the comparison
Console.WriteLine("Points are equal: " & arePointsEqual)
End Sub
End Class
Explanation
- Namespaces and Libraries:
System
andSystem.Drawing
are used for basic functionalities and to access thePoint
class, respectively.
- Creating Points:
- Two
Point
objects,point1
andpoint2
, are instantiated with identical coordinates (10, 20).
- Two
- Equals() Method:
point1.Equals(point2)
invokes theEquals()
method on thepoint1
object to compare it withpoint2
.- This method checks if both the x and y coordinates of
point1
andpoint2
are identical.
- Output:
Console.WriteLine
prints whether the two points are equal, which, in this case, outputs "true".
It's important to note that this method can only be used with Point
objects of the same class. Attempting to use this method to compare two points of different classes, such as comparing Point
and PointF
classes, will result in a NullReferenceException
being thrown at runtime.