Matias Cicero
Matias Cicero

Reputation: 26281

Anonymous types for simple interfaces with only one implementation

Let's suppose I have the following the interface:

public interface IMyInterface {
     A MyA { get; }
     B MyB { get; }
     C MyC { get; }
}

A, B and C are three non-related classes, and don't implement IMyInterface in any way.

Let's suppose now that I will only have one implementation for this interface. I might have wanted to create it for mocking purposes, even if it's just composed of properties.

I have designed the following factory:

public static class MyManagerFactory {
    public static IMyManager CreateMyManager() {
        //Return the implementation
    }
}

I don't want to create a whole new file and type for just an implementation of properties, so I was looking for an anonymous type:

var anon = new {
    MyA = new A(),
    MyB = new B(),
    MyC = new C()
};

But I cannot return anon because it's of type object and the compiler can't know I'm implementing my interface.

So I thought of doing a cast:

IMyInterface casted = anon as IMyInterface;

But this won't compile either, stating:

Cannot convert type 'AnonymousType#1' to 'IMyInterface' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.

I thought the as conversion is supposed to be done at runtime, and if (for any reason) fails, it would simply return null.

But this error is compile time.

How can I return a IMyInterface instance?

Upvotes: 0

Views: 92

Answers (3)

dcastro
dcastro

Reputation: 68640

I might have wanted to create it for mocking purposes,

I don't want to create a whole new file and type for just an implementation of properties, so I was looking for an anonymous type:

If it's just for mocking purposes, then you can just create a nested private implementation of that interface, no need for a whole new file

public class MyClassTests
{

    private class MyDummyImplementation : IMyInterface { ... }    

    [Fact]
    public void Test()
    {
        var x = new MyDummyImplementation();
    }

}

Upvotes: 2

Boas Enkler
Boas Enkler

Reputation: 12557

This is not possible as the type does not implement the interface. It just hasthe methods of the interface "by coincidence"

C# doesn't look if methods are presents it check if the type is defined as implementing the interface.

Upvotes: 3

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

This could be a nice feature or not, but currently C# doesn't support anonymously-implemented interface on anonymous objects.

If you look for further info, you'll see that Java has this feature (for example see this Q&A here in StackOverflow: How can an anonymous class use "extends" or "implements"?).

At least C# 6 won't include this feature. From my point of view, it could be very useful and in my humble opinion, it's the unique Java feature I would steal to implement in C#.

Upvotes: 1

Related Questions