The only thing I can think of is as follows, which is far from ideal:
interface IBar {
void Foo() => Console.WriteLine("Hello from interface!");
}
struct Baz : IBar {
// compiler error
void Test1() => this.Foo();
// IIRC this will box
void Test2() => ((IBar)this).Foo();
// this shouldn't box but is pretty complicated just to call a method
void Test3() {
impl(ref this);
void impl<T>(ref T self) where T : IBar
=> self.Foo();
}
}
Is there a more straightforward way to do this?
(Related and how I got to this question: Calling C# interface default method from implementing class)
Haven't set myself up for c# 8.0 yet, so I'm not sure this'll work, but here's an idea you could try:
I don't think there are any allocations. This answer to this possibly duplicate question explains that the JIT compiler can avoid boxing in many cases, including explicit interface implementation calls. Andy Ayers from the JIT team verified this in a comment and provided a link to the PR that implemented this.
I adapted the code in that answer :
The results don't show any allocations :
I changed the return type to an int just like the linked answer to ensure the method won't be optimized away