Click here to Skip to main content
15,890,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can I initialize a protected member of the base class through the object of the derived class without providing its set and get properties?
Posted
Updated 26-Aug-13 1:14am
v2

1 solution

Yes - and no.
You can access it in the derived class:
C#
public class Base
    {
    protected string myString;
    }
public class Derived : Base
    {
    public Derived()
        {
        myString = "Hello World";
        }
    }

but you can't access it from outside either via the instance object:
C#
private void MyMethod()
    {
    Derived d = new Derived();
    d.myString = "goodbye";  //'MyNameSpace.Base.myString' is inaccessible due to its protection level
    }
Unless you encapsulate it in a property and specify the setter and getter:
C#
private void MyMethod()
        {
        Derived d = new Derived();
        d.MyString = "goodbye";   //All fine
        }
    ...
public class Base
    {
    protected string myString;
    }
public class Derived : Base
    {
    public string MyString { get { return myString; } set { myString = value; } }
    public Derived()
        {
        myString = "Hello World";
        }
    }
 
Share this answer
 
Comments
[no name] 26-Aug-13 7:17am    
perfect Answer
Innocent910 26-Aug-13 7:39am    
gud ans...help me alot thnx
OriginalGriff 26-Aug-13 7:53am    
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