Checking against null in Equals() - c#

How come if I comment out the second line when overriding Equals() like so:
public override bool Equals(object obj) {
if(object.ReferenceEquals(this, obj)) return true;
//if(obj == null) return false;
Person other = obj as Person;
if(other == null) return false;
return this.Name == other.Name;
}
I get a NullReferenceException? If I uncomment it, it'll work. Also I made sure that the obj argument wasn't a null, and it still does that.
Here is full code
namespace MyNameSpace{
class Person : IComparable<Person>{
public string Name { get; set; }
public Person(string name) {
Name = name;
}
public static bool operator <(Person x, Person y) {
return x.CompareTo(y) < 0;
}
public static bool operator >(Person x, Person y) {
return x.CompareTo(y) > 0;
}
public static bool operator ==(Person x, Person y) {
return x.Equals(y);
}
public static bool operator !=(Person x, Person y) {
return !x.Equals(y);
}
public override bool Equals(object obj) {
if(object.ReferenceEquals(this, obj)) return true;
//if(obj == null) return false;
Person other = obj as Person;
if(other == null) return false;
return this.Name == other.Name;
}
public int CompareTo(Person other) {
return this.Name.CompareTo(other.Name);
}
}
class Program {
static void Main(string[] args) {
Person one = new Person("one");
Person two = new Person("two");
Console.WriteLine(one == two);
}
}
}

I suspect you have a custom == operator on Person, which is being invoked by the line:
if(other == null) return false;
Which also hints that the operator is buggy and should be fixed.
Edit: and with your update: here is the buggy custom == operator:
public static bool operator ==(Person x, Person y) {
return x.Equals(y);
}
Using just:
public static bool operator ==(Person x, Person y) {
return Equals(x,y);
}
would solve that, along with:
public override bool Equals(object obj) {
if(obj == (object)this) return true; // ref equality, the cheap way
if(obj is Person) {
Person other = (Person)obj;
return this.Name == other.Name;
}
return false;
}

As a general rule for IComparable implementation, I would strongly recommend Eric Lippert's approach. It's very simple and helps a lot to not get NRE.
Basically, you don't call either Equals or == in any operator overload. You just call a unique static method that does all the job:
public int CompareTo(Natural x) { return CompareTo(this, x); }
public static bool operator <(Natural x, Natural y) { return CompareTo(x, y) < 0; }
public static bool operator >(Natural x, Natural y) { return CompareTo(x, y) > 0; }
public static bool operator <=(Natural x, Natural y) { return CompareTo(x, y) <= 0; }
public static bool operator >=(Natural x, Natural y) { return CompareTo(x, y) >= 0; }
public static bool operator ==(Natural x, Natural y) { return CompareTo(x, y) == 0; }
public static bool operator !=(Natural x, Natural y) { return CompareTo(x, y) != 0; }
public override bool Equals(object obj) { return CompareTo(this, obj as Natural) == 0; }
public bool Equals(Natural x) { return CompareTo(this, x) == 0; }
// negative means x < y
// positive means x > y
// zero means x == y
// two nulls are equal
// otherwise, null is always smaller
private static int CompareTo(Natural x, Natural y) {
if (ReferenceEquals(x, y))
return 0;
else if (ReferenceEquals(x, null))
return -1;
else if (ReferenceEquals(y, null))
return 1;
else if (ReferenceEquals(x, Zero))
return -1;
else if (ReferenceEquals(y, Zero))
return 1;
else if (x.head == y.head)
return CompareTo(x.tail, y.tail);
else if (x.head == ZeroBit)
return CompareTo(x.tail, y.tail) > 0 ? 1 : -1;
else
return CompareTo(x.tail, y.tail) < 0 ? -1 : 1;
}

I get it, I was recursively calling operator ==, and at some point i had operator == (x, y), where x and y were both null, and then I did x.Equals(), that's why it threw that exception.

Related

C# Dictionary that uses an Unordered Pair as its Key?

I'm trying to create a Dictionary is C# that takes an Unordered Pair of Indices as its Key.
For example:
exampleDictionary[new UnorderedPair(x,y)] and exampleDictionary[new UnorderedPair(y,x)] should both return the same value.
Is there a way to create a custom unordered collection other than using a HashSet? Or some way to create an unordered Tuple?
This question is similar to what I'm trying to accomplish, except in C# rather than python.
If the type is not your own or you can't or don't want to modify refer to Theodor Zoulias's answer
Otherwise, assuming that UnorderedPair is your own class you can modify what you could do is e.g.
[Serializable]
public class UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
public T X;
public T Y;
public UnorderedPair()
{
}
public UnorderedPair(T x, T y)
{
X = x;
Y = y;
}
public bool Equals(UnorderedPair<T> other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
// For equality simply include the swapped check
return X.Equals(other.X) && Y.Equals(other.Y) || X.Equals(other.Y) && Y.Equals(other.X);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((UnorderedPair<T>)obj);
}
public override int GetHashCode()
{
// and for the HashCode (used as key in HashSet and Dictionary) simply order them by size an hash them again ^^
var hashX = X == null ? 0 : X.GetHashCode();
var hashY = Y == null ? 0 : Y.GetHashCode();
return HashCode.Combine(Math.Min(hashX,hashY), Math.Max(hashX,hashY));
}
public static bool operator ==(UnorderedPair<T> left, UnorderedPair<T> right)
{
return Equals(left, right);
}
public static bool operator !=(UnorderedPair<T> left, UnorderedPair<T> right)
{
return !Equals(left, right);
}
}
and then e.g.
var testDict = new Dictionary<UnorderedPair<int>, string>();
testDict.Add(new UnorderedPair<int>(1,2), "Hello World!");
Console.WriteLine(testDict[new UnorderedPair<int>(2,1)]);
As per suggestion by Jodrell in the comments you could even make the types swappable - not sure this would be ever needed - but this way you could even have a pair of different types:
[Serializable]
public class UnorderedPair<TX, TY> : IEquatable<UnorderedPair<TX, TY>>
{
public TX X;
public TY Y;
public UnorderedPair()
{
}
public UnorderedPair(TX x, TY y)
{
X = x;
Y = y;
}
public UnorderedPair(TY y, TX x)
{
X = x;
Y = y;
}
public override int GetHashCode()
{
// and for the HashCode (used as key in HashSet and Dictionary) simply order them by size an hash them again ^^
var hashX = X == null ? 0 : X.GetHashCode();
var hashY = Y == null ? 0 : Y.GetHashCode();
var combine = HashCode.Combine(Math.Min(hashX, hashY), Math.Max(hashX, hashY));
return combine;
}
public bool Equals(UnorderedPair<TX, TY> other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (typeof(TX) != typeof(TY))
{
return EqualityComparer<TX>.Default.Equals(X, other.X) && EqualityComparer<TY>.Default.Equals(Y, other.Y);
}
return EqualityComparer<TX>.Default.Equals(X, other.X) && EqualityComparer<TY>.Default.Equals(Y, other.Y)
|| X.Equals(other.Y) && Y.Equals(other.X);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return obj switch
{
UnorderedPair<TX, TY> other => Equals(other),
UnorderedPair<TY, TX> otherSwapped => Equals(otherSwapped),
_ => false
};
}
public static bool operator ==(UnorderedPair<TX, TY> left, UnorderedPair<TX, TY> right)
{
return Equals(left, right);
}
public static bool operator !=(UnorderedPair<TX, TY> left, UnorderedPair<TX, TY> right)
{
return !Equals(left, right);
}
public static implicit operator UnorderedPair<TX, TY>(UnorderedPair<TY, TX> pair)
{
return new UnorderedPair<TX, TY>(pair.Y, pair.X);
}
}
and
var testDict = new Dictionary<UnorderedPair<int, double>, string>();
testDict.Add(new UnorderedPair<int, double>(1,2.5), "Hello World!");
Console.WriteLine(testDict[new UnorderedPair<double,int>(2.5,1)]);
(.NET Fiddle for both)
You could write a custom IEqualityComparer<UnorderedPair<T>> implementation, and pass it as argument to the constructor of your Dictionary<UnorderedPair<TKey>, TValue>. This way you won't have to modify your UnorderedPair<T> type, by overriding its Equals and GetHashCode methods. Below is an example of such a comparer for the ValueTuple<T1, T2> struct, with both T1 and T2 being the same type:
class UnorderedValueTupleEqualityComparer<T> : IEqualityComparer<(T, T)>
{
private readonly IEqualityComparer<T> _comparer;
public UnorderedValueTupleEqualityComparer(IEqualityComparer<T> comparer = default)
{
_comparer = comparer ?? EqualityComparer<T>.Default;
}
public bool Equals((T, T) x, (T, T) y)
{
if (_comparer.Equals(x.Item1, y.Item1)
&& _comparer.Equals(x.Item2, y.Item2)) return true;
if (_comparer.Equals(x.Item1, y.Item2)
&& _comparer.Equals(x.Item2, y.Item1)) return true;
return false;
}
public int GetHashCode((T, T) obj)
{
int h1 = _comparer.GetHashCode(obj.Item1);
int h2 = _comparer.GetHashCode(obj.Item2);
if (h1 > h2) (h1, h2) = (h2, h1);
return HashCode.Combine(h1, h2);
}
}
Usage example:
Dictionary<(int, int), string> dictionary = new(
new UnorderedValueTupleEqualityComparer<int>());
Inspired by #derHugo's answer and my comments on it,
Fiddle here
A generic implementation,
#nullable enable
public class UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
private static IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
public T X { get; }
public T Y { get; }
public UnorderedPair(T x, T y)
{
X = x;
Y = y;
}
public bool Equals(UnorderedPair<T>? other)
{
if(other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
// For equality simply include the swapped check
return
comparer.Equals(X, other.X) && comparer.Equals(Y, other.Y)
||
comparer.Equals(X, other.Y) && comparer.Equals(Y, other.X);
}
public override bool Equals(object? obj)
{
return Equals(obj as UnorderedPair<T>);
}
public override int GetHashCode()
{
unchecked
{
return
(X is null ? 0 : comparer.GetHashCode(X))
+
(Y is null ? 0 : comparer.GetHashCode(Y));
}
}
public static bool operator ==(UnorderedPair<T>? left, UnorderedPair<T>? right)
{
return Equals(left, right);
}
public static bool operator !=(UnorderedPair<T>? left, UnorderedPair<T>? right)
{
return !Equals(left, right);
}
}
#nullable disable

How to handle nulls in IEqualityComparer?

The following method is from XUnit Assert class:
public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer);
And I am using it as:
IEnumerable<Decimal?> x = getXValues();
IEnumerable<Decimal?> y = getYValues();
Assert.Equal(x, y, new DecimalToleranceEqualityComparer(0.01m));
I am using an IEqualityComparer because is fine to consider 2.526 equal to 2.524.
I get an error because DecimalToleranceEqualityComparer is only for Decimal ...
x and y might have null values. DecimalToleranceEqualityComparer is:
public class DecimalToleranceEqualityComparer : IEqualityComparer<Decimal> {
private readonly Decimal _tolerance;
public DecimalToleranceEqualityComparer(Decimal tolerance) {
_tolerance = tolerance;
}
public Boolean Equals(Decimal x, Decimal y) {
return Math.Abs(x - y) <= _tolerance;
}
public Int32 GetHashCode(Decimal obj) {
return obj.GetHashCode();
}
}
I suppose if 2 values are nulls they should be consider equal ...
How to change the IEqualityComparer so that it handles nulls?
This code works for me. The real trick is in the imlementation of the Equals method. Also keep in mind the null check in the GetHashCode.
static void Main(string[] args)
{
IEnumerable<Decimal?> x = new List<Decimal?> { 1.51m, 3, null };
IEnumerable<Decimal?> y = new List<Decimal?> { 1.6m, 3, null };
Assert.Equal(x, y, new DecimalToleranceEqualityComparer(0.1m));
}
public class DecimalToleranceEqualityComparer : IEqualityComparer<Decimal?>
{
private readonly Decimal _tolerance;
public DecimalToleranceEqualityComparer(Decimal tolerance)
{
_tolerance = tolerance;
}
public Boolean Equals(Decimal? x, Decimal? y)
{
if (!x.HasValue && !y.HasValue)
{
// Both null -> they are equal
return true;
}
else if (!x.HasValue || !y.HasValue)
{
// One is null, other is not null -> not equal
return false;
}
else
{
// both have values -> run the actual comparison
return Math.Abs(x.Value - y.Value) <= _tolerance;
}
}
public Int32 GetHashCode(Decimal? obj)
{
if (obj.HasValue)
{
return obj.GetHashCode();
}
else
{
// Here decide what you need
return string.Empty.GetHashCode();
}
}
}
One option that comes to mind could be implementing new equality comparer for nullable decimal type IEqualityComparer<decimal?> which could use your existing DecimalToleranceEqualityComparer internally. Something like
public Boolean Equals(Decimal? x, Decimal? y) {
return (x.HasValue && y.HasValue)?
_decimalToleranceEqualityComparer.Equals(x.Value,y.Value)
: x == y;
}
You are supplying a list of Nullable<decimal>'s and your IEqualityComparer is expecting a list of Decimal's.
With a rewrite like this you should be fine:
public class DecimalToleranceEqualityComparer : IEqualityComparer<decimal?>
{
private readonly decimal _tolerance;
public DecimalToleranceEqualityComparer(decimal tolerance)
{
_tolerance = tolerance;
}
public bool Equals(decimal? x, decimal? y)
{
if (!x.HasValue && !y.HasValue) return true;
if (!x.HasValue || !y.HasValue) return false;
return Math.Abs(x.Value - y.Value) <= _tolerance;
}
public int GetHashCode(decimal? obj)
{
return obj.GetHashCode();
}
}

Question regarding declaration of equality operators in C#

This seems incredibly basic, but I couldn't find any other answers on this particular note. In declaring a == operator in C#, you must also declare the != operator. Obviously every case may vary based on type, but if a type has explicit equality or does not, is it reasonable to declare != as simply !(a == b)? Is there a reason NOT to do this? For example:
public static bool operator ==(Point p1, Point p2)
{
return ((p1.X == p2.x) && (p1.Y == p2.Y));
}
public static bool operator !=(Point p1, Point p2)
{
return !(p1 == p2);
}
There is a good example from Microsoft Docs: How to: Define Value Equality for a Type covering important aspects of defining equality for types.
In the following example, for x!=y you see it's simply returning !(x==y):
using System;
class TwoDPoint : IEquatable<TwoDPoint>
{
// Readonly auto-implemented properties.
public int X { get; private set; }
public int Y { get; private set; }
// Set the properties in the constructor.
public TwoDPoint(int x, int y)
{
if ((x < 1) || (x > 2000) || (y < 1) || (y > 2000))
{
throw new System.ArgumentException("Point must be in range 1 - 2000");
}
this.X = x;
this.Y = y;
}
public override bool Equals(object obj)
{
return this.Equals(obj as TwoDPoint);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null, return false.
if (Object.ReferenceEquals(p, null))
{
return false;
}
// Optimization for a common success case.
if (Object.ReferenceEquals(this, p))
{
return true;
}
// If run-time types are not exactly the same, return false.
if (this.GetType() != p.GetType())
{
return false;
}
// Return true if the fields match.
// Note that the base class is not invoked because it is
// System.Object, which defines Equals as reference equality.
return (X == p.X) && (Y == p.Y);
}
public override int GetHashCode()
{
return X * 0x00010000 + Y;
}
public static bool operator ==(TwoDPoint lhs, TwoDPoint rhs)
{
// Check for null on left side.
if (Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null))
{
// null == null = true.
return true;
}
// Only the left side is null.
return false;
}
// Equals handles case of null on right side.
return lhs.Equals(rhs);
}
public static bool operator !=(TwoDPoint lhs, TwoDPoint rhs)
{
return !(lhs == rhs);
}
}

How this switch case has unreachable code?

I was implementing some generic IEqualityComparer<T> Equal() method when the code in the switch is unreachable without visible reason for me:
public bool Equals(T x, T y)
{
switch (nameof(T))
{
case nameof(Accessory):
return (x as Accessory).Id == (y as Accessory).Id;//not reachable
default:
return false;
}
}
Someone has a clue?
nameof evaluates the name of the T at compile time, so it's a constant string, "T", and thus only the default case will ever be taken.
Here's an alternative implementation:
public bool Equals(T x, T y)
{
if (x is Accessory && y is Accessory)
{
var ax = x as Accessory;
var ay = y as Accessory;
return ax.Id == ay.Id;
}
return false;
}
C# 7.1 introduces some syntactic sugar:
public bool Equals(T x, T y)
{
if (x is Accessory ax && y is Accessory ay)
{
return ax.Id == ay.Id;
}
return false;
}
(Note that your excerpt returns false if both x and y are null; I haven't fixed this in my versions.)
Can use this. This checks for null x and y:
public bool Equals(T x, T y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType()
!= y.GetType()) return false;
return x.Id == y.Id;
}

How to represent integer infinity?

I need a way to represent an integer number that can be infinite. I'd prefer not to use a floating point type (double.PositiveInfinity) since the number can never be fractional and this might make the API confusing. What is the best way to do this?
Edit: One idea I haven't seen yet is using int? with null representing infinity. Are there any good reasons not to do this?
If you don't need the full range of integer values, you can use the int.MaxValue and int.MinValue constants to represent infinities.
However, if the full range of values is required, I'd suggest either creating a wrapper class or simply going for doubles.
An example partial implementation along the lines of the comments of SLaks and others (feedback welcome):
Usage:
int x = 4;
iint pi = iint.PositiveInfinity;
iint ni = iint.NegativeInfinity;
Assert.IsTrue(x + pi == iint.PositiveInfinity);
Assert.IsTrue(pi + 1 == iint.PositiveInfinity);
Assert.IsTrue(pi + (-ni) == iint.PositiveInfinity);
Assert.IsTrue((int)((iint)5) == 5);
Implementation:
public struct iint
{
private readonly int _int;
public iint(int value)
{
if(value == int.MaxValue || value == int.MinValue)
throw new InvalidOperationException("min/max value reserved in iint");
_int = value;
}
public static explicit operator int(iint #this)
{
if(#this._int == int.MaxValue || #this._int == int.MinValue)
throw new InvalidOperationException("cannot implicit convert infinite iint to int");
return #this._int;
}
public static implicit operator iint(int other)
{
if(other == int.MaxValue || other == int.MinValue)
throw new InvalidOperationException("cannot implicit convert max-value into to iint");
return new iint(other);
}
public bool IsPositiveInfinity {get { return _int == int.MaxValue; } }
public bool IsNegativeInfinity { get { return _int == int.MinValue; } }
private iint(bool positive)
{
if (positive)
_int = int.MaxValue;
else
_int = int.MinValue;
}
public static readonly iint PositiveInfinity = new iint(true);
public static readonly iint NegativeInfinity = new iint(false);
public static bool operator ==(iint a, iint b)
{
return a._int == b._int;
}
public static bool operator !=(iint a, iint b)
{
return a._int != b._int;
}
public static iint operator +(iint a, iint b)
{
if (a.IsPositiveInfinity && b.IsNegativeInfinity)
throw new InvalidOperationException();
if (b.IsPositiveInfinity && a.IsNegativeInfinity)
throw new InvalidOperationException();
if (a.IsPositiveInfinity)
return PositiveInfinity;
if (a.IsNegativeInfinity)
return NegativeInfinity;
if (b.IsPositiveInfinity)
return PositiveInfinity;
if (b.IsNegativeInfinity)
return NegativeInfinity;
return a._int + b._int;
}
public static iint operator -(iint a, iint b)
{
if (a.IsPositiveInfinity && b.IsPositiveInfinity)
throw new InvalidOperationException();
if (a.IsNegativeInfinity && b.IsNegativeInfinity)
throw new InvalidOperationException();
if (a.IsPositiveInfinity)
return PositiveInfinity;
if (a.IsNegativeInfinity)
return NegativeInfinity;
if (b.IsPositiveInfinity)
return NegativeInfinity;
if (b.IsNegativeInfinity)
return PositiveInfinity;
return a._int - b._int;
}
public static iint operator -(iint a)
{
if (a.IsNegativeInfinity)
return PositiveInfinity;
if (a.IsPositiveInfinity)
return NegativeInfinity;
return -a;
}
/* etc... */
/* other operators here */
}
Your API can use a convention that int.MaxValue represents positive infinity value and int.MinValue - negative infinity.
But you still need to document it somewhere and, may be you will need some operations with your infinite integer:
/// <summary>
/// Making int infinity
/// ...
/// </summary>
public static class IntExtension
{
public const int PositiveInfinity = int.MaxValue;
public const int NegativeInfinity = int.MinValue;
public static bool IsPositiveInfinity(this int x)
{
return x == PositiveInfinity;
}
public static bool IsNegativeInfinity(this int x)
{
return x == NegativeInfinity;
}
public static int Operation(this int x, int y)
{
// ...
return PositiveInfinity;
}
}
Another partial implementation (I see Jack was faster):
struct InfinityInt
{
readonly int Value;
InfinityInt(int value, bool allowInfinities)
{
if (!allowInfinities && (value == int.MinValue || value == int.MaxValue))
throw new ArgumentOutOfRangeException("value");
Value = value;
}
public InfinityInt(int value)
: this(value, false)
{
}
public static InfinityInt PositiveInfinity = new InfinityInt(int.MaxValue, true);
public static InfinityInt NegativeInfinity = new InfinityInt(int.MinValue, true);
public bool IsAnInfinity
{
get { return Value == int.MaxValue || Value == int.MinValue; }
}
public override string ToString()
{
if (Value == int.MinValue)
return double.NegativeInfinity.ToString();
if (Value == int.MaxValue)
return double.PositiveInfinity.ToString();
return Value.ToString();
}
public static explicit operator int(InfinityInt ii)
{
if (ii.IsAnInfinity)
throw new OverflowException();
return ii.Value;
}
public static explicit operator double(InfinityInt ii)
{
if (ii.Value == int.MinValue)
return double.NegativeInfinity;
if (ii.Value == int.MaxValue)
return double.PositiveInfinity;
return ii.Value;
}
public static explicit operator InfinityInt(int i)
{
return new InfinityInt(i); // can throw
}
public static explicit operator InfinityInt(double d)
{
if (double.IsNaN(d))
throw new ArgumentException("NaN not supported", "d");
if (d >= int.MaxValue)
return PositiveInfinity;
if (d <= int.MinValue)
return NegativeInfinity;
return new InfinityInt((int)d);
}
static InfinityInt FromLongSafely(long x)
{
if (x >= int.MaxValue)
return PositiveInfinity;
if (x <= int.MinValue)
return NegativeInfinity;
return new InfinityInt((int)x);
}
public static InfinityInt operator +(InfinityInt a, InfinityInt b)
{
if (a.IsAnInfinity || b.IsAnInfinity)
{
if (!b.IsAnInfinity)
return a;
if (!a.IsAnInfinity)
return b;
if (a.Value == b.Value)
return a;
throw new ArithmeticException("Undefined");
}
return FromLongSafely((long)a.Value + (long)b.Value);
}
public static InfinityInt operator *(InfinityInt a, InfinityInt b)
{
if (a.IsAnInfinity || b.IsAnInfinity)
{
if (a.Value == 0 || b.Value == 0)
throw new ArithmeticException("Undefined");
return (a.Value > 0) == (b.Value > 0) ? PositiveInfinity : NegativeInfinity;
}
return FromLongSafely((long)a.Value * (long)b.Value);
}
// and so on, and so on
}
C# has a type for this the BigInteger class is unlimited size
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx
If you want the class to have a representation of infinity -- then wrap BigInteger in a class that gives it an infinity flag.
You will have to redefine all standard operators and conversions to get this to work.
How exactly to have operations on infinity work depends on your domain.
(For example in some forms of math you would like 2 x infinity = infinity and in some you don't).
How the details are implemented really depend on your domain problem and are not clear from your question.

Categories

Resources