Skip to content

Provide "static virtual interface members" with examples and description of static virtual methods #43130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
public struct Duplicate : IGetDuplicated<Duplicate>
{
public int _num;

public Duplicate(int num)
{
_num = num;
}

public static Duplicate operator ++(Duplicate other)
=> other with { _num = other._num + other._num };

public override string ToString() => _num.ToString();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public interface IGetDuplicated<T> where T : IGetDuplicated<T>
{
static virtual T operator ++(T other) => throw new NotImplementedException();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to think through this and use a different example for a static virtual (not abstract) method. That's because in practice, if the only reasonable implementation in the interface declaration is to throw a NotImplementedException, that indicates that it should be abstract.

Maybe consider an interface that provides < and >, but assumes that T implements IComparable<T>. Something like:

public interface IArithmeticComparable<T> where T : IComparable<T>
{
    static virtual bool operator > (T left, T right) => left.CompareTo(right) > 0;

// etc.
}

I know that adds a bit more concepts to explain, so I'm open to any alternative example. That's just the first obvious one that came to my mind.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is valid point, @BillWagner, thanks! But it looks like my knowledge is missing something, because my question is: What would be the use case of such implementation? In other words how to call the static virtual defined in an interface without any definition in the type implementing that interface? I know I'm asking kinda for an implementation details, but can you point me some examples of such use cases or implementations?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it's difficult to have a good scenario here @BartoszKlonowski

That's why I suggested the < and > operators. That's the one scenario I could think of where this works. It's not great, but it's reasonable.

Or, since any static method could be used, something like this might work:

public interface ISingleton<T> where T : new()
{
    public static virtual T Instance
    {
        get
        {
            field ??= new T();
            return field;
        }
        private set
        {
            field = value;
        }
    }
}

I have concerns here as well, because it uses a preview feature. But maybe we can adapt it somehow to do something like Lazy<T>, but use a static virtual method.

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@
Console.WriteLine(str++);
// </TestRepeat>

// <TestDuplication>
var num = new Duplicate(2);
num++;
Console.WriteLine(num.ToString());
// </TestDuplication>

// <TestAddition>
var pt = new Point<int>(3, 4);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,26 @@ AAAAAAAAAA

This small example demonstrates the motivation for this feature. You can use natural syntax for operators, constant values, and other static operations. You can explore these techniques when you create multiple types that rely on static members, including overloaded operators. Define the interfaces that match your types' capabilities and then declare those types' support for the new interface.

## Static virtual interface methods

Similar can be achieved using the static virtual methods of an interface. This is done with the syntax of `static` and `virtual` modifiers added to any member that should be implemented in the type implementing that interface. The following example defines the `IGetDuplicated<T>` interface, providing any type with a constraint that a type will implement the `operator ++`:

:::code language="csharp" source="./snippets/staticinterfaces/GetDuplicated.cs":::

Because virtual methods aren't abstract, they must declare their body. However, for now it's throwing the `NotImplementedException` exception by default, to highlight the lack of implementation.

The next snippet creates a structure that implements the `IGetDuplicated<T>` interface. This `Duplicate` structure uses the `++` operator implementation to duplicate the initial number given when creating the structure:

:::code language="csharp" source="./snippets/staticinterfaces/Duplicate.cs":::

You can use this `Duplicate` type by calling the `operator ++`:

:::code language="csharp" source="./snippets/staticinterfaces/Program.cs" id="TestDuplication":::

which will print the result of `4`.

Note that without having the `operator ++` implemented, calling `num++` would still not compile, leading to [CS0023](../../misc/cs0023.md). Reason for that is that even if we have the default implementation in the static virtual method of an interface, this is still only an interface and the type implementing that interface has no such operator implemented.

## Generic math

The motivating scenario for allowing static methods, including operators, in interfaces is to support [generic math](../../../standard/generics/math.md) algorithms. The .NET 7 base class library contains interface definitions for many arithmetic operators, and derived interfaces that combine many arithmetic operators in an `INumber<T>` interface. Let's apply those types to build a `Point<T>` record that can use any numeric type for `T`. The point can be moved by some `XOffset` and `YOffset` using the `+` operator.
Expand Down
Loading