Search code examples
winformsnamespace-organisationglobal-namespace

Conditional Namespace in Winform application


I want to know better way to define name-spaces in my projects. We have 2 different winform projects and there are certain code files and forms which we use in both project. So the structure of project 1 and 2 is below:

//Project Pro1
//-------------------------------------
//Class C1 starts
#if pro1
using pro1
#endif
#if pro2
using pro2
#endif
namespace common_fun
{
Class C1
    Method M1
    {
        call to C2.M2
    }

}

//Class C2 starts
namespace pro1
{
Class C2
    Method M2

}

//Project Pro2
//----------------


#if pro1
using pro1
#endif
#if pro2
using pro2
#endif
namespace common_fun
{
Class C1
    Method M1
    {
        call to C2.M2
    }

}

namespace pro2
{
Class C2
    Method M2

}

So here, class C1 (under namespace common_fun) is shared file used in both projects. But in that we need to call method M2 of class C2 and for calling that method we need to write conditional using statements on top. i.e.

#if pro1
using pro1
#elseif pro2
using pro2
#endif

So my question is there any better way to include namespaces for common files? as in future there might be 3-4 projects that will use the same classes / forms.

Thanks.


Solution

  • I would make a common interface that contains your M2 method:

     interface ICommonFun
     {
          void M2();
     }
    

    Then pass the implementation of that interface to your C1 class:

     class C1
     {
          ICommonFun Instance;
    
          public void M1()
          { 
             Instance.M2();
          }
    
          public C1(ICommonFun fun)
          {
              Instance = fun;
          }
      }