Skip to main content

RCS1241: Implement non-generic counterpart

Properties

PropertyValue
Default SeverityHidden
Minimum language version-

Summary

Publicly visible type that implements IComparable<T>, IComparer<T> or IEqualityComparer<T> should implement their non-generic counterpart.

Examples

Example #1

diagnostic.cs
using System;
using System.Collections.Generic;

public class C
{
}

public abstract class Comparable : IComparable<C>
{
public abstract int CompareTo(C other);
}
fix.cs
using System;
using System.Collections.Generic;

public class C
{
}

public abstract class Comparable : IComparable<C>, IComparable
{
public abstract int CompareTo(C other);

public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}

if (obj is C x)
{
return CompareTo(x);
}

throw new ArgumentException("""", nameof(obj));
}
}

Example #2

diagnostic.cs
using System;
using System.Collections;
using System.Collections.Generic;

public class C
{
}

public abstract class Comparer : IComparer<C>
{
public abstract int Compare(C x, C y);
}
fix.cs
using System;
using System.Collections;
using System.Collections.Generic;

public class C
{
}

public abstract class Comparer : IComparer<C>, IComparer
{
public abstract int Compare(C x, C y);

public int Compare(object x, object y)
{
if (x == y)
{
return 0;
}

if (x == null)
{
return -1;
}

if (y == null)
{
return 1;
}

if (x is global::C a
&& y is global::C b)
{
return Compare(a, b);
}

if (x is IComparable ic)
{
return ic.CompareTo(y);
}

throw new ArgumentException("""", nameof(x));
}
}

Example #3

diagnostic.cs
using System;
using System.Collections;
using System.Collections.Generic;

public class C
{
}

public abstract class EqualityComparer : IEqualityComparer<C>
{
public abstract bool Equals(C x, C y);

public abstract int GetHashCode(C obj);
}
fix.cs
using System;
using System.Collections;
using System.Collections.Generic;

public class C
{
}

public abstract class EqualityComparer : IEqualityComparer<C>, IEqualityComparer
{
public abstract bool Equals(C x, C y);

public abstract int GetHashCode(C obj);

new public bool Equals(object x, object y)
{
if (x == y)
{
return true;
}

if (x == null || y == null)
{
return false;
}

if (x is global::C a
&& y is global::C b)
{
return Equals(a, b);
}

return x.Equals(y);
}

public int GetHashCode(object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}

if (obj is C x)
{
return GetHashCode(x);
}

return obj.GetHashCode();
}
}

Applies to