How would you implement a “trait” design-pattern in C#?

You can get the syntax by using marker interfaces and extension methods. Prerequisite: the interfaces need to define the contract which is later used by the extension method. Basically the interface defines the contract for being able to “implement” a trait; ideally the class where you add the interface should already have all members of … Read more

Default implementation in interface is not seen by the compiler?

Methods are only available on the interface, not the class. So you can do this instead: IJsonAble request = new SumRequest() var result = request.ToJson(); Or: ((IJsonAble)new SumRequest()).ToJson(); The reason for this is it allows you to add to the interface without worrying about the downstream consequences. For example, the ToJson method may already exist … Read more

Calling C# interface default method from implementing class

See the documentation at https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/default-interface-members-versions That cast from SampleCustomer to ICustomer is necessary. The SampleCustomer class doesn’t need to provide an implementation for ComputeLoyaltyDiscount; that’s provided by the ICustomer interface. However, the SampleCustomer class doesn’t inherit members from its interfaces. That rule hasn’t changed. In order to call any method declared and implemented in the … Read more

Can a C# class call an interface’s default interface method from its own implementation?

As far as I know you can’t invoke default interface method implementation in inheriting class (though there were proposals). But you can call it from inheriting interface: public class HappyGreeter : IGreeter { private interface IWorkAround : IGreeter { public void SayHello(string name) { (this as IGreeter).SayHello(name); System.Console.WriteLine(“I hope you’re doing great!!”); } } private … Read more

Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?

Conceptual First of all, there is a conceptual difference between a class and an interface. A class should describe an “is a” relationship. E.g. a Ferrari is a Car An interface should describe a contract of a type. E.g. A Car has a steering wheel. Currently abstract classes are sometimes used for code reuse, even … Read more