9

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

azrosen92
  • 8,357
  • 4
  • 26
  • 45
  • 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. – Dai Jul 17 '13 at 19:27
  • 1
    With a mocking framework you can create an instance, for example `new Mock()`. You might want to setup concrete implementations of the methods which the mocking framework might do from a delegate. – Jeppe Stig Nielsen Jul 17 '13 at 19:33
  • possible duplicate of [Is there a C# equivalent of this?](http://stackoverflow.com/questions/15581737/is-there-a-c-sharp-equivalent-of-this) – nawfal Jun 28 '14 at 18:42

7 Answers7

13

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

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • It will be compiled as a anonymous class. – Sriram Sakthivel Jul 17 '13 at 19:28
  • 7
    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. – Lasse V. Karlsen Jul 17 '13 at 19:29
  • @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. – Michael Jul 14 '14 at 16:25
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

4

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()

oakio
  • 1,868
  • 1
  • 14
  • 21
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.

mkoertgen
  • 898
  • 6
  • 14
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.

Tim
  • 14,999
  • 1
  • 45
  • 68
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();
Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42
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.

Chad
  • 7,279
  • 2
  • 24
  • 34