There is some black magic code in c# where you can define the default implementation of an interface.
So you can write
var instance = new ISomeInterface();
Any pointers?
UPDATE 1: Note that I did not ask if this is a good idea. Just how was it possible to do it.
UPDATE 2: to anyone seeing the accepted answer.
Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.
Default interface methods enable an API author to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface. The feature enables C# to interoperate with APIs targeting Android (Java) and iOS (Swift), which support similar features.
With C# 8.0, you can now have default implementations of methods in an interface. Interface members can be private, protected, and static as well. Protected members of an interface cannot be accessed in the class that extends the interface.
You specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. All method declarations in an interface, including default methods, are implicitly public , so you can omit the public modifier.
Here comes the black magic:
class Program { static void Main() { IFoo foo = new IFoo("black magic"); foo.Bar(); } } [ComImport] [Guid("C8AEBD72-8CAF-43B0-8507-FAB55C937E8A")] [CoClass(typeof(FooImpl))] public interface IFoo { void Bar(); } public class FooImpl : IFoo { private readonly string _text; public FooImpl(string text) { _text = text; } public void Bar() { Console.WriteLine(_text); } }
Notice that not only you can instantiate an interface but also pass arguments to its constructor :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With