teenup
teenup

Reputation: 7667

Two projects, a derived class should be able to access one method but not the other one

I was asked this question in interview, but couldn't answer it.

There are two projects: P1 and P2

P1 has a class A with methods M1 and M2

P2 has a class B and class C, both of these classes (inherit or reference)* from class A in Project P1

Class B should be able to access method M1 but not M2 Class C should be able to access method M2 but not M1

*I don't remember if he said inherit or said reference

How can this be done?

Upvotes: 0

Views: 53

Answers (2)

janmbaco
janmbaco

Reputation: 350

You can implement some like: https://dotnetfiddle.net/0mYxdU

public interface InterfaceCommon
{
    void Function();
}

public class Implementacion1 : InterfaceCommon
{
    public void Function()
    {
        Console.WriteLine("I am Method1");
    }
}

public class Implementacion2 : InterfaceCommon
{
    public void Function()
    {
        Console.WriteLine("I am Method2");
    }
}

public abstract class A
{
    private readonly InterfaceCommon interfaceCommon;

    protected A(InterfaceCommon interfaceCommon)
    {
        this.interfaceCommon = interfaceCommon;
    }

    public void  CallFunction()
    {
        interfaceCommon.Function();
    }

}


public class B : A
{
   public B() : base(new Implementacion1()) {  }

}

public class C : A
{
    public C() : base(new Implementacion2()) { }

}

public class Program
{
    public static void Main(string[] args)
    {
        var b = new B();
        b.CallFunction();
        var c = new C();
        c.CallFunction();
        Console.ReadLine();
    }
}

Upvotes: 1

Simon Kocurek
Simon Kocurek

Reputation: 2166

You want to use interfaces to extract methods from class.

P1:

public interface IM1
{
  void M1();
}

public interface IM2
{
  void M2();
}

// Not public
internal class A : IM1, IM2
{
   public void M1() {} 
   public void M2() {}
}

P2:

public class B
{
   private readonly IM1 _m1;
}

public class C
{
   private readonly IM2 _m2;
}

Upvotes: 1

Related Questions