10

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

3
  • 2
    Java is still creating a class behind-the-scenes, it's just syntactic sugar - and in a way, their solution to a lack of delegates/function pointers. Commented Jul 17, 2013 at 19:27
  • 1
    With a mocking framework you can create an instance, for example new Mock<ITokenStore>(). You might want to setup concrete implementations of the methods which the mocking framework might do from a delegate. Commented Jul 17, 2013 at 19:33
  • possible duplicate of Is there a C# equivalent of this? Commented Jun 28, 2014 at 18:42

7 Answers 7

14

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

Sign up to request clarification or add additional context in comments.

3 Comments

It will be compiled as a anonymous class.
No, you cannot do this in .NET/C#, and to be clear, you can't do it in Java either. What the compiler does in Java is to build the anonymous type for you, a type implementing the interface. So Java has a shortcut to getting that type, C# doesn't.
@LasseV.Karlsen While C# may not, MS's C# compiler does: see oakio's answer below. It's just not part of any spec (and its use is limited at best), so it's really not a good idea to use.
5

If you really want this:

    private static void Main(string[] args)
    {
        IFoo foo = new IFoo(); // <- interface
        foo.Print();

        Console.ReadKey();
    }


    [ComImport, Guid("A7D5E89D-8FBD-44B7-A300-21FAB4833C00"), CoClass(typeof(Foo))]
    public interface IFoo
    {
        void Print();
    }

    public class Foo : IFoo
    {
        public void Print()
        {
            Console.WriteLine("Hello!");
        }
    }

But if you open compiled assembly on ildasm.exe, you will see:

IL_0001: newobj instance void TestApp.Program/Foo::.ctor()

Comments

4

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

Comments

2

As far as i know .NET does not have the Java concept of anonymous inner classes. There is a typical need for dynamic implementations of an interface in unit testing scenarios. So may be a look on some dynamic mocking frameworks may be interesting for you, for instance

  1. Impromptu Interface (includes support for dynamic)
  2. Moq

Have a look on NuGet gallery for packages tagged with mocking.

Comments

0

You can't create an instance of an interface in C#. You must create an instance of a class/type that implements that interface.

Might want to go read up on interfaces in C#. There's no way to "fake" it like Java does.

I'm kind if intrigued by this concept though since it is something available in another language. I suppose you could use an anonymous class with delegate parameters if your consumer knew how to fake duck typing. But that hardly seems worth it.

Comments

0

Something like this:

public class MyTokenStore: ITokenStore
{
    public IToken CreateRequestToken(IOAuthContext context)
    {
        ...some code here...
    }
    public IToken CreateAccessToken(IOAuthContext context)
    {
        ...some code here...
    }
}

Then use it:

ITokenStore x = new MyTokenStore();

Comments

0

Like the others have said, no, this is not possible.

However, you could write one generalized class that has delegates for each method. Something like the following:

public class DelegateTokenStore : ITokenStore
{
    public delegate IToken TokenCreator(IOAuthContext context);
    public TokenCreator RequestTokenCreator { get; set; }
    public TokenCreator AccessTokenCreator { get; set; }

    public IToken CreateRequestToken(IOAuthContext context)
    {
        return RequestTokenCreator(context);
    }

    public IToken CreateAccessToken(IOAuthContext context)
    {
        return AccessTokenCreator(context);
    }
}

Then you could use it like this:

ITokenStore tokenStore = new DelegateTokenStore()
{
    RequestTokenCreator = (context) =>
    {
        IToken requestToken = null;
        return requestToken;
    },
    AccessTokenCreator = (context) =>
    {
        IToken accessToken = null;
        return accessToken;
    },
};

I'm not saying it's necessarily a good idea to take this approach. Like anything, the appropriateness depends on your use case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.