Possible Duplicate:
Why are private fields private to the type, not the instance?
Consider the following class:
public class Test
{
protected string name;
private DateTime dateTime;
public Test(string name)
{
this.name = name;
this.dateTime = DateTime.Now;
}
public Test(Test otherObject)
{
this.name = otherObject.name;
this.dateTime = otherObject.GetDateTime();
}
private DateTime GetDateTime()
{
return dateTime;
}
public override string ToString()
{
return name + ":" + dateTime.Ticks.ToString();
}
}
In my constructor I'm calling private or protected stuff of the otherObject
. Why is this possible? I always thought private was really private (implying only the object could call that method / variable) or protected (only accessible by overloads).
Why and when would I have to use a feature like this?
Is there some OO-logic / principle that I'm missing?
private: The type or member can be accessed only by code in the same class or struct . protected: The type or member can be accessed only by code in the same class , or in a class that is derived from that class .
C# Protected: Using the Protected Keyword in C# public means that your object's method can be called from anywhere, or that the instance variable that you declare public can be accessed from anywhere, whether outside or inside the class itself.
No, absolutely not. Frob. Foo is protected; it should only be accessible from Frob and subclasses of Frob.
'Protected' means that it's visible from within the class and any classes that inherits it, 'void' means it has no return value, and 'Page_Load' is the name of the method.
From MSDN (C# Reference)
The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.
To answer your question:
You can use that for example in a Clone method. Where you need write access to members which may be exposed as read only. Like
class MyClass : ICloneable
{
public object Clone()
{
var clone = (MyClass)MemberwiseClone();
clone.Value = this.Value; // without the way private works, this would not be possible
return clone;
}
public int Value{ get; private set;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With