Single.Equals() Method in C# with Examples

The Single.Equals() method in C# is used to return a value indicating whether two instances of Single represent the same value. The Single type is an alias for float in C#, so this method compares floating-point values for equality.

Syntax

The Single.Equals() method has two overloads −

public bool Equals(float obj);
public override bool Equals(object obj);

Parameters

obj − The object or float value to compare with the current instance.

Return Value

Returns true if the specified value is equal to the current instance; otherwise, false. For the object overload, it also returns false if the object is not a Single type or is null.

Using Equals() with Float Values

This example demonstrates comparing two different float values −

using System;

public class Demo {
   public static void Main() {
      float f1 = 15.9f;
      float f2 = 40.2f;
      Console.WriteLine("Value1 = " + f1);
      Console.WriteLine("Value2 = " + f2);
      Console.WriteLine("Are both the values equal? = " + f1.Equals(f2));
   }
}

The output of the above code is −

Value1 = 15.9
Value2 = 40.2
Are both the values equal? = False

Using Equals() with Object Parameter

This example demonstrates the object overload with equal values −

using System;

public class Demo {
   public static void Main() {
      float f1 = 10.9f;
      object f2 = 10.9f;
      Console.WriteLine("Value1 = " + f1);
      Console.WriteLine("Value2 = " + f2);
      Console.WriteLine("Are both the values equal? = " + f1.Equals(f2));
   }
}

The output of the above code is −

Value1 = 10.9
Value2 = 10.9
Are both the values equal? = True

Special Cases with NaN and Infinity

The Equals()NaN and Infinity

using System;

public class Demo {
   public static void Main() {
      float nan1 = float.NaN;
      float nan2 = float.NaN;
      float positiveInf = float.PositiveInfinity;
      float negativeInf = float.NegativeInfinity;
      
      Console.WriteLine("NaN equals NaN: " + nan1.Equals(nan2));
      Console.WriteLine("PositiveInfinity equals PositiveInfinity: " + positiveInf.Equals(float.PositiveInfinity));
      Console.WriteLine("PositiveInfinity equals NegativeInfinity: " + positiveInf.Equals(negativeInf));
   }
}

The output of the above code is −

NaN equals NaN: True
PositiveInfinity equals PositiveInfinity: True
PositiveInfinity equals NegativeInfinity: False

Conclusion

The Single.Equals() method provides a reliable way to compare floating-point values for exact equality. Unlike the == operator, it properly handles special cases like NaN values and provides type-safe comparison when used with the object overload.

Updated on: 2026-03-17T07:04:36+05:30

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements