I encoutered a somewhat (at least for me) strange behaviour in a library I'm building;
I have this method:
public class Lib
{
private string field = "field";
public string Field
{
get
{
return field;
}
}
public void Add(Lib lib)
{
string field = DoSomething(lib);
Console.WriteLine(field);
}
protected string DoSomething(Lib lib)
{
return lib.field;
}
}
So, if I call the method from a program that uses the library:
Lib lib = new Lib();
Lib lib2 = new Lib();
lib.Add(lib2);
The Console gives me "field" as output... Now, I don't quite understand why that happens. I declared the field as private, so why can one class access the other classes' private property and it doesn't give me an Exception about access-restrictions?!
In my understanding, a Lib can access it's own fields anyways, but when I give the method an other instance of Lib, it should not be possible for the first instance to access the seconds' private fields, because... well, because it's an other instance and private!