Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance of a interface in c#

Tags:

c#

interface

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#?

like image 574
azrosen92 Avatar asked Jul 17 '13 19:07

azrosen92


People also ask

How do I create an instance of an interface?

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”.

Can we create instance of interface class?

You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance.

Can we create an object of an interface?

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.

Can you create an instance of an interface using its constructor?

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.


2 Answers

The only way to "Create an instance of a interface in c#" is to create an instance of a type implementing the interface.

like image 177
Lasse V. Karlsen Avatar answered Sep 30 '22 03:09

Lasse V. Karlsen


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

like image 25
Sam I am says Reinstate Monica Avatar answered Sep 30 '22 02:09

Sam I am says Reinstate Monica