Bug
Bug

Reputation: 942

Class implements interface and expose it as property

Do you think the following code create some circular reference?

public interface IMyInterface
{
       
}

public class MyClass : IMyInterface
{
    public IMyInterface  MyInterface { get; set; }
}

public class AnotherClass : IMyInterface
{

}

Upvotes: 2

Views: 62

Answers (3)

Alpha75
Alpha75

Reputation: 2280

There isn't any circular reference. Indeed, you have two simple concrete classes that implements an interface. And one of them, MyClass, acts as a wrapper of itself, a very used pattern.

You can find this kind of wrappers in different design patterns as the Adapter, or Decorator, where you maintain a inner instance of the interface to decorate with additional behavior or change it completely.

Also, simple wrapper can acts as a layer to isolate two coupled dependencies or as an anticorruption layer.

Upvotes: 1

AMunim
AMunim

Reputation: 1161

No, it does not create a circular reference, your class can inherit an interface 'foo' and have another 'foo' that has different implementation.


public interface Foo{ }

public class Bar: Foo {}

public class Baz : Foo
{
   public Foo foo;
   public Baz()
   {
       foo = new Bar();
   }
}

Even if it is the same type it will work, if they are different instances.

public Bar: Foo
{
   public Foo bar;
   public Bar()
   {

   }

   //this works because they are different instances of the same object.
   public void AddBar(Bar bar)
   {
      this.bar = bar;
   }
}

Even if you have the same instance it shouldn't break, because that's how the Singleton pattern works, you create a static property that holds the static instance of the same class.

Upvotes: 2

Mosia Thabo
Mosia Thabo

Reputation: 4267

The way you done it using Interface is the right way to do it. No circular reference will occur.

Here's another similar question answered here on OS here

Furthermore, here's another detailed example from Tutorials point

Upvotes: 2

Related Questions