Interface implementation with class member #7643
-
Hi! This proposal is about implementing interface by property of class to avoid redundant mappings. The possible appearance could be the following: public interface IInterface
{
public void Method1();
public void Method2();
}
public class InternalImplementor : IInterface
{
public void Method1() => Console.WriteLine("Hello1");
public void Method2() => Console.WriteLine("Hello2");
}
public class ExposedImplementor : IInterface
{
[DefaultImplementation]
IInterface Implementation { get; } = new InternalImplementor();
public void Method2() => Console.WriteLine("Hello3");
} Which essentially can be translated to: public class ExposedImplementor : IInterface
{
IInterface Implementation { get; } = new InternalImplementor();
public void Method1() => Implementation.Method1();
public void Method2() => Console.WriteLine("Hello3");
} Of course, the exact way it is provided may be different, but I guess the general idea is understandable. Also, I believe it'd be cheap to implement due to the possibility of expression with existing elements at the compile time. Usefulness lies in the fact that such a compact syntax will make it significantly easier to prefer composition instead of inheritance, which is generally beneficial in most cases. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
See: #234 |
Beta Was this translation helpful? Give feedback.
-
This seems easy to achieve with a source generator. |
Beta Was this translation helpful? Give feedback.
-
Taking your example, this can already be achieved with default interface members (DIM's): public interface IInterface
{
public void Method1() => Console.WriteLine("Hello1");
public void Method2() => Console.WriteLine("Hello2");
}
public class ExposedImplementor : IInterface
{
public void Method2() => Console.WriteLine("Hello3");
} Do you have an example of why DIMs don't fully solve your need here? |
Beta Was this translation helpful? Give feedback.
See: #234