I am using an interface in C# and rather than write an entirely new class which implements that interface is it possible to just create an object which implements that interface? The interface is defined as
public interface ITokenStore
{
IToken CreateRequestToken(IOAuthContext context);
IToken CreateAccessToken(IOAuthContext context);
}
And I know in java I could something like
ITokenStore tokenStore = new ITokenStore()
{
IToken CreateRequestToken(IOAuthContext context) {
IToken requestToken = null;
return requestToken;
}
IToken CreateAccessToken(IOAuthToken context) {
IToken accessToken = null;
return accessToken;
}
};
Is there an equivalent way to instantiate in instance of an interface in c#?
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.
You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance.
Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) Interface methods do not have a body - the body is provided by the "implement" class. On implementation of an interface, you must override all of its methods.
No, you cannot have a constructor within an interface in Java. You can have only public, static, final variables and, public, abstract, methods as of Java7. From Java8 onwards interfaces allow default methods and static methods. From Java9 onwards interfaces allow private and private static methods.
The only way to "Create an instance of a interface in c#" is to create an instance of a type implementing the interface.
Interfaces have no logic in them by design. They simply don't actually do anything.
Instantiating one without an implementing class doesn't even make sense
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