tags:

views:

71

answers:

4

Hi, I am newbie in C#.

Could you please help me to understand the difference from a private method and a protected one. Following http://msdn.microsoft.com/en-us/library/ba0a1yw2%28v=VS.71%29.aspx I am not able to understand it, specially the phrase "Private: Access is limited to the containing type."

Thanks for your help. Bye!

+6  A: 
class Test
{
  private method myMethod()
   {}
  protected method myprotectedMethod()
   {}
}


class ChildTest : Test
{
  public method useProtectedBaseMethod ()
  {
     this.myProtectedMethod(); // this is ok
     this.myMethod(); // this is NOT ok. will throw an Error
  }
}

class outsider
{
  Test  objTest = new Test();
  objTest.myProtectedMethod(); // throws an error as it is not accessible
  objTest.myMethod(); // throws an error as it is not accessible
}
InSane
Simple and Clear, really thanks for your time!
GIbboK
@GIbboK - Glad to be of use :-)
InSane
+2  A: 

A private member is only accessible (visible) to the "containing type", that is to the class itself.

A protected member is accessible to the containing class and derived classes

Henk Holterman
Just to make it clear to me. A protected member is accessible more widely that a private??
GIbboK
@GIbboK: That's right.
BoltClock
OK guys really thanks for help! Sounds more clear now! :-)
GIbboK
+1  A: 

private - only visible in the class' scope

protected - visible to inheritors of the class.

protected may be combined with internal : A class member is then visible within the same assembly or in any other if you inherit from the class in question.

flq
I see nothing wrong with this answer. Why the downvote?
BoltClock
Wrong – `protected internal` means that it is accessible from the same assembly **or** from inheritors.
svick
svick is right...protected internal does not mean you only allow inheritance in the same assembly.
Dismissile
yup, true, looks like I wasn't paying attention.
flq
@flq, you should then edit your answer
svick
A: 
class A
{
   private void DoPrivate()
   {
   }

   protected void DoProtected()
   {
      DoPrivate();
   }
}

class B : A
{
    public void CallMethods()
    {
       DoProtected(); // Succeeded
       DoPrivate(); // you can't do it its not contain the method DoPrivate()

       A a = new A();
       a.DoProtected(); // Succeeded
       a.DoProtected(); // you can't do it its not contain the method DoPrivate() in B
    }
}
SaeedAlg