0

Possible Duplicate:
Why are private fields private to the type, not the instance?

Consider the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Foo foo = new Foo();
            Foo foo2 = new Foo();
            foo.Test(foo);

            Console.ReadLine();

        }
    }


    public class Foo
    {
        public void Test(Foo foo)
        {
            Console.WriteLine("I was called");
            foo.test_fuction();
        }

        private void test_fuction()
        {
            Console.WriteLine("!");
        }


    }

}

In this case, I would expect that the private keyword would prevent the instance's member variables and functions from being accessed. Wouldn't this allow someone to write some poorly written round-about access to some objects? Is there a way to prevent this behaviour? Or is it intended for a good reason?

Community
  • 1
  • 1
Vaughan Hilts
  • 2,839
  • 1
  • 20
  • 39
  • Sheesh, I see everything showing up under 'Related' now. I wonder why it didn't show up under Google. Thanks for that clear thread. – Vaughan Hilts Jan 28 '13 at 21:37
  • Yeah, this is the second question today where I've read someone is having a problem with the search. – JoshDM Jan 28 '13 at 22:34

1 Answers1

0

Private means the member is accessible within the body of the type in which it is declared, not only accessible to a given instance.

There is no way to prevent this behavior. Static methods would be much less useful if only a particular instance could access private members.

From section 3.5.2 of the spec:

The accessibility domain of a nested member M declared in a type T within a program P is defined as follows (noting that M itself may possibly be a type):

  • If the declared accessibility of M is private, the accessibility domain of M is the program text of T.
Community
  • 1
  • 1
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122