Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is calling a protected or private CSharp method / variable possible? [duplicate]

Tags:

c#

.net

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?

like image 752
Kees C. Bakker Avatar asked Oct 11 '11 10:10

Kees C. Bakker


People also ask

What is the difference between private and protected in C#?

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 .

What does Protected Variable Mean C#?

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.

Can protected variables be inherited in C#?

No, absolutely not. Frob. Foo is protected; it should only be accessible from Frob and subclasses of Frob.

What does protected void mean C#?

'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.


2 Answers

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.

like image 193
KV Prajapati Avatar answered Oct 12 '22 08:10

KV Prajapati


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;}
}
like image 3
dowhilefor Avatar answered Oct 12 '22 09:10

dowhilefor