user7360479
user7360479

Reputation:

How to access protected member in an inherited class

I have 2 classes:

public class Access
{
    public class Job
    {
        public int Id { get; set; }
        protected string JobName { get; set; }
    }
}

Class2.cs

public class Full: Access.Job
{

}

Full ful = new Full();

Why I'm not able to access the ful.JobName member?

Upvotes: 1

Views: 4794

Answers (1)

Tatranskymedved
Tatranskymedved

Reputation: 4381

Because You are trying to access protected method from outside the class. Only public methods are available. You can access the property/variably/method that is protected, only in the inherited class, but not from outer code:

public class Full: Access.Job
{
    public void mVoid()
    {
        Console.WriteLine(this.JobName);
    }

    protected void mProtVoid()
    {
        Console.WriteLine(this.JobName);
    }

    private void mPrivateVoid()
    {
        Console.WriteLine("Hey");
    }
}

Full myFull = new Full();
myFull.mVoid();  //will work
myFull.mProtVoid(); //Will not work
myFull.mPrivateVoid(); //Will not work

If You need to get to the protected property, there are 2 ways (3 actually, but Reflection is the dirty way and should be avoided):

1. Make it public

If it will be set to public, it will be stil inherit and You can directly access it:

Full nFull = new Full();
Console.Write(nFull.JobName);

2. Make a "wrapper"/"facade"

Create new property or method, that will just access the hidden property and return it in expected format.

public class Full: Access.Job
{
    public string WrappedJobName { get { return this.JobName; } }
    public string WrappedJobName => this.JobName; //C# 6.0 syntax
}

Full mFull = new Full();
Console.WriteLine(mFull.WrappedJobName);

Upvotes: 4

Related Questions