4

I want to do the exactly the same thing described here, but in C#.

public interface IFoo { void DoSomething(); }

public class Foo : IFoo
{
    public void DoSomething() {...}
    protected void Bar() {...}
}

public class Foo2 : IFoo
{
    private readonly Foo _foo;

    public Foo2 (Foo foo) { _foo = foo; }

    public void DoSomething() {...}

    protected void Bar()
    {
        _foo.Bar(); // cannot access Bar() from here
    }
}

I looked at several similar questions, but none of them really tell you exactly how to solve this problem. Is trying to decorate a class with protected method a wrong thing to do in the first place?

Community
  • 1
  • 1
CookieEater
  • 2,237
  • 3
  • 29
  • 54
  • The entire idea about `protected` is that it is only accessible in the current class and its subclasses. You will never be able to access it in a class that just holds a reference to it, both in Java and C#. – Jeroen Vannevel Feb 08 '14 at 15:57
  • related question http://stackoverflow.com/a/614844/682480 – Code Maverick Feb 08 '14 at 15:59

3 Answers3

5

Protected methods are only visible to subclasses. If Foo and Foo2 are in the same assembly you can make Foo.Bar internal instead:

public class Foo
{
    internal void Bar() { ... }
}
Lee
  • 142,018
  • 20
  • 234
  • 287
0

The only difference is that protected methods can be used in derived classes and private methods cannot. So it's not a matter of right or wrong, but rather it's a matter of whether or not you need that functionality.

See this SO answer for more clarification.

Community
  • 1
  • 1
Code Maverick
  • 20,171
  • 12
  • 62
  • 114
0

You may make intermediate class FooInternal:

public interface IFoo { void DoSomething(); }

public class Foo : IFoo
{
    public void DoSomething() {}
    protected void Bar() {}
}

public class FooInternal : Foo
{
    internal void Bar()
    {
        base.Bar();
    }
}

public class Foo2 : IFoo
{
    private readonly FooInternal _foo;

    public Foo2(FooInternal foo) { _foo = foo; }

    public void DoSomething() {}

    protected void Bar()
    {
        _foo.Bar(); // can access Bar() from here
    }
}
neodim
  • 468
  • 4
  • 15