Incorrect question: Explicit interfaces aren't explicit. Allow override keyword in interfaces? #8275
-
Let we have single-significant property in interface: public interface IReadOnlyBit : IEquatable<IReadOnlyBit>
{
protected abstract bool Value { get; }
...
} I found only three ways how we can get rid of code duplication:
public interface IReadOnlyBit : IEquatable<IReadOnlyBit>
{
protected abstract bool Value { get; }
bool IEquatable<IReadOnlyBit>.Equals(IReadOnlyBit? other) => Value.Equals(other?.Value);
...
}
public interface IReadOnlyBit : IEquatable<IReadOnlyBit> {
protected abstract IReadOnlyValue<bool> Value { get; }
bool IEquatable<IReadOnlyBit>.Equals(IReadOnlyBit? other) => Value.Equals(other?.Value);
}
public interface IValue<T> : IEquatable<T> {
public required T Value { get; init; }
public bool IEquatable(T? other) => Value.Equals(other?.Value);
}
public interface IReadOnlyBit : IEquatable<IReadOnlyBit>
{
protected abstract bool Value { get; }
new public virtual bool Equals(IReadOnlyBit? other) => Value.Equals(other?.Value);
}
public struct ReadOnlyBit : IReadOnlyBit // CS0535
{
bool IReadOnlyBit.Value { get; }
} Second one means either: public struct ReadOnlyBit : IReadOnlyBit
{
bool IReadOnlyBit.Value => false; // For test
}
public static void Main() {
IReadOnlyBit bit = new ReadOnlyBit(true);
IReadOnlyBit bit2 = new ReadOnlyBit(true);
bool same = bit.Equals(bit2); // Correct
Console.Write(same); // false
} The problem is we have explicit interface implimentation, but using implicit. Let we have following instead? public interface IReadOnlyBit : IEquatable<IReadOnlyBit>
{
public override bool Equals(IReadOnlyBit other) => Value.Equals(other?.Value); // CS0106
...
} ...when: namespace System;
public interface IEquatable<T>
{
abstract bool Equals(T? other);
} This code is also embarrassing: public interface IReadOnlyBit2 : IReadOnlyBit
{
protected override bool Value { get; } // CS0106
override bool IReadOnlyBit.Value { get; } // CS0106
bool IReadOnlyBit.Value { get { ... } } // Ok
...
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Mention that I'd suggest you to clarify what you are trying to approach. Do you want |
Beta Was this translation helpful? Give feedback.
-
Okay. |
Beta Was this translation helpful? Give feedback.
Mention that
IEquatable<T>
with different T's are different interface implementations. Many of your snippets don't compile due to the mismatch ofIEquatable<T>
implementation.In interface, default implementation for other interface methods needs to be explicit. This is different with the context of classes/structs.
I'd suggest you to clarify what you are trying to approach. Do you want
IReadOnlyBit
to carry the default implementation ofEquals
that checks the single significantValue
?