Click here to Skip to main content
15,906,645 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when members f class declared as private then how the set and get property works????
give me ans with simple examples that could understand easily... thnx
Posted

1 solution

When you declare them as private, they can only be accessed from within that class, and no other:
C#
public class MyBase
    {
    private string MyProp { get; set; }
    public void Method(string s) { MyProp = s; }
    public string OtherMethod() { return MyProp; }
    }
public class MyDerived : MyBase
    {
    public void SetIt()
        {
        MyProp = "hello";  // **** ERROR ****
        Method("Hello");   // OK
        }
    }
Even if you derive a new class from MyBase, the new class cannot access the private members. To allow that, you can declare it as protected:
C#
{
    protected string MyProp { get; set; }
    public void Method(string s) { MyProp = s; }
    public string OtherMethod() { return MyProp; }
    }
public class MyDerived : MyBase
    {
    public void SetIt()
        {
        MyProp = "hello";   // OK
        Method("Hello");    // OK
        }
    }

Anything declared within a class is available anywhere within that class regardless of the protection level, but you can restrict access to it outside the class, using the private, protected and internal specifiers.
 
Share this answer
 
Comments
[no name] 24-Aug-13 3:24am    
My VOTE 5 to this solution.
Innocent910 24-Aug-13 3:45am    
thank u bro
OriginalGriff 24-Aug-13 4:35am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900