51

I have the following classes:

namespace Bla.Bla 
{
    public abstract class ClassA 
    {
        public virtual void Setup(string thing) 
        {
        }

        public abstract bool IsThingValid();

        public abstract void ReadThings();

        public virtual void MatchThings() { }

        public virtual void SaveThings() { }

        public void Run(string thing) 
        {
            Setup(thing);

            if (!IsThingValid()) 
            {

            }

            ReadThings();
            MatchThings();
            SaveThings();
        }
    }
}

namespace Bla.Bla 
{
    public class ClassB : ClassA 
    {
        ClassB() { } 

        public override void IsThingValid() 
        {
            throw new NotImplementedException();
        }

        public override void ReadThings() 
        {
            throw new NotImplementedException();
        }
    }
}

Now I try to do the following:

public class ClassC 
{
    public void Main() 
    {
        var thing = new ClassB();
        ClassB.Run("thing");
    }
}

Which returns the following error: ClassB is inaccessible due to its protection level.

But they are all public.

jao
  • 18,273
  • 15
  • 63
  • 96

3 Answers3

112

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Also if you want to do something like ClassB.Run("thing");, make sure the Method Run(); is static or you could call it like this: thing.Run("thing");.

0

You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.

Eric Milliot-Martinez
  • 4,076
  • 3
  • 23
  • 28