Home > front end >  How can I access values in another class inherited from public class C#?
How can I access values in another class inherited from public class C#?

Time:08-29

I get an error when inheriting from public class I can't access values of another class.

AppEngine.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestEngine
{
    public class AppEngine : Appstrings
    {
        public async Task<string> Testing()
        {
            return wrongUserName;
        }
    }
}

Appstrings.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestEngine
{
    public class Appstrings
    {
        string wrongUserName = "Wrong username. Please check and try again..";
    }
}

I want to access the values that I defined in the Appstrings class by inheriting them from the AppEngine class. This is the code I wrote, but the error I get is 'Appstrings.wrongUserName' is inaccessible due to its protection level. It is said that it cannot be inherited due to protection, but the class construction is public. Where do you think I am doing wrong?

CodePudding user response:

Base on C# language reference

Class members can have any of the five kinds of declared accessibility and default to private declared accessibility.

So, the wrongUserName has the private accessibility inside the Appstrings class. You must specify the accessibility of the member explicitly to internal, protected, or public (not recommended).

namespace TestEngine
{
    public class Appstrings
    {
        protected string wrongUserName = "Wrong username. Please check and try again..";
    }
}

CodePudding user response:

Access modifiers also apply to properties. If you don't set one it's implicitely set to private. So if you want to set it to public you'll need to add it infront of the property, although protected would also work if you only want to make it accessable by inheritance:

public string wrongUsername = "...";

See Microsoft docs for the complete list of access modifiers.

  • Related