-2

I have below two classes in two projects and each class needs to call other class method. But cannot add reference to each other because it is creating a circular dependency.

I know that i must use a interface to resolve the issue but i am not able comeup with answer. Please let me know how to implement & resolve this.

project Test2

 namespace Test2
    {
       public  class ClassTest2 
        {
            public string GetClassTest2()
            {
                return "classTest2";
            }
        }
    }

Project Test1

namespace Test1
{
   public class ClassTest1
   {
        public string GetClassTest1()
        {
            return "classTest1";
        }
    }
}
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
  • 1
    How will your individual classes be getting an instance of the other class? – Paddy Oct 17 '14 at 13:28
  • 3
    The code samples add nothing here - they in no way seem to represent the actual problem scenario since all they show are two completely independent classes. Also, please explain what obstacle prevents you from placing both classes inside a single project. – Damien_The_Unbeliever Oct 17 '14 at 13:28
  • possible duplicate of [How to solve circular reference?](http://stackoverflow.com/questions/6928387/how-to-solve-circular-reference) – Christian Oct 17 '14 at 13:29
  • Is it not possible to call GetClassTest2 from Test1 and GetClassTest1 from Test2 – fernandos fernandos Oct 17 '14 at 13:31
  • Learn about how to decouple your code using [events](http://msdn.microsoft.com/en-us/library/awbftdfh.aspx). – spender Oct 17 '14 at 13:46

1 Answers1

1

You'd need a third project in which you define the interface:

public interface IClassNameAware
{
    string GetClassName();
}

From both existing projects, reference this new assembly and make the classes implement the interface:

public class ClassTest1 : IClassNameAware
{
    public string GetClassName()
    {
        return "classTest1";
    }

Now both classes still can't access eachother directly, but they do accept IClassNameAware variables, ie:

    public bool ClassNamesEqual(IClassNameAware otherClass)
    {
        return GetClassName().Equals(otherClass.GetClassName());
    }
}
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • An alternative to this would be to create a separate assembly to hold the interface for first class and the second class. However any design that requires this 'hack' to accomplish needs to be rethought out. – Cameron Oct 17 '14 at 15:57
  • @Cameron It's quite common to have an interface defined in a separate assembly (I referred to it as "project" because that's the term the OP used). Think about ADO.NET and the separate providers. It would also make sense to create an implementation that wraps another underlying implementation to add a layer of abstraction. The OP didn't share his intent, but I disagree it being a hack per se. – C.Evenhuis Oct 17 '14 at 17:56