user6734269
user6734269

Reputation:

Implement method in another project

Is it possible to declare a method's class in a project and implement in another ? Something like :

namespace projectA
{
    Class A
    {
        void toImplement()
        {
            //TODO
        }
        void print()
        {
              toImplement();
        }
    }
}
namespace projectB
{
    A.toImplement()
    {
        // print “projectB"
    }
}
namespace projectC
{
    A.toImplement()
    {
        // print “projectC"
    }
}

I don't want to create a new class with inheritance, because I want to use the method in class A. But if I define the method in a project K, the method will do the same that if I call from project B.

Upvotes: 2

Views: 475

Answers (3)

mcfedr
mcfedr

Reputation: 7975

So my guess is the reason you don't want to make A abstract and implement it in the other projects is because you want to be able to do new A() in the library.

In this case, the solution therefore, is to use the Factory Pattern.

You make the method abstract, and you declare a factory interface.

namespace projectA {
    Class A
    {
        abstract void toImplement();
    }

    Interface AFactory
    {
        A create()
    }
}

Then in your project that uses this you have your implementation of A and make a factory.

namespace projectB
{
    Class RealA extends A
    {
        void toImplement() { does stuff }
    }

    Class RealAFactory implements AFactory
    {
        A create() { return new RealA() }
    }
}

You now just need to pass the factory to the library when initalising it or at some logically point in time. Now projectA can get a new instance of RealA whenever it needs from RealAFactory.

Upvotes: 0

TripleEEE
TripleEEE

Reputation: 509

You can write an Extension function see MSDN: Extension Function

For just adding methods to it, - as you described in your second code example - you could use a partial class

public static class B_Extensions
{
   public static void SetString(this A a, string s)
   {
      a.Astring = s;
   }
}

public class A
{
   public string Astring { get; set; }
}
// In any other class
private void DoSomething()
{
    var a = new A();
    a.SetString("Something");
}

Partial Class: - put those in the same project

 public partial class A
 {
    public void SetString(string s)
    {
       Astring = s;
    }
 }

 public partial class A
 {
     public string Astring { get; set; }
 }

Upvotes: 2

Sefe
Sefe

Reputation: 14007

You can create an abstract method, but it will have to be public to be accessible in another project:

namespace projectA
{
    public abstract Class A
    {
        public abstract void toImplement();
    }
}

namespace projectB
{
    public Class B : A
    {
        public override void toImplement()
        {
            //Implement here
        }
    }
}

Upvotes: 3

Related Questions