Home > Back-end >  Class implements interface and expose it as property
Class implements interface and expose it as property

Time:07-17

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
{

}

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c#
  • Related