Public class is inaccessible due to its protection level - c#

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.

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.

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");.

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.

Related

Accessing a private method in a overridden public method

I am currently having some issues with accessing a private method from a overriden public method.
My situation is like this: I have a compiled .dll file which consist basically of this
public class OriginalHandler
{
public virtual void Request()
{
RedirectIfConditionIsFulfilled()
this.PeformRequest()
}
protected virtual bool PeformRequest()
{
}
private static void RedirectIfConditionIsFulfilled()
{
}
}
I need to alter the method PeformRequest(), So i make a public class, which inherit OriginalHandler and override the method as such:
public class ModifiedOriginalHandler : OriginalHandler
{
protected override bool PeformRequest()
{
}
}
To ensure that this method doesn't violate an "impact" scope, I have to ensure that it only get evaluated on certain sites,
We use this to ensure that HttpRequestProcess ONLY impact the desired site using this
namespace Sitecore.Sharedsource.Pipelines.HttpRequest
{
using System.Collections.Generic;
using Assert = Sitecore.Diagnostics.Assert;
using S = Sitecore;
public abstract class SiteSpecificHttpRequestProcessor: S.Pipelines.HttpRequest.HttpRequestProcessor
{
public abstract List<string> _sites;
public sealed override void Process(S.Pipelines.HttpRequest.HttpRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (S.Context.Site == null || !this._sites.FirstOrDefault(S.Context.Site.Name))
{
return;
}
this.DoProcess(args, this._sites.FirstOrDefault(S.Context.Site.Name));
}
protected abstract void DoProcess(S.Pipelines.HttpRequest.HttpRequestArgs args, string);
}
}
So include my ModifiedOriginalHandler to include this
public class SiteSpecificModifiedOriginalHandler: SiteSpecificHttpRequestProcessor
{
Public override List<String> _sites => new[]
{
"www.only.com" , "www.boat.com"
};
public virtual HttpContext GetHttpContext()
{
return HttpContext.Current;
}
public override void DoProcess(HttpRequestArgs args, string)
{
var mediaRequest = new ModifiedOriginalHandler ();
var context = GetHttpContext();
var site = Sitecore.Context.Site;
if (site == null)
{
return;
}
if (string != null)
{
mediaRequest.Request(context);
}
else
{
OriginalHandler baseClass = mediaRequest;
baseClass.Request(context);
}
}
}
This Is where I am having a problem, I can from the SiteSpecificModifiedOriginalHandler not call the protected method PeformRequest,
but can call the public method Request which internally calls the desired function, so I make an override function,
to ensure that the original is not being called but my modified version
public class ModifiedOriginalHandler : OriginalHandler
{
protected override bool PeformRequest()
{
}
public override void Request()
{
RedirectIfConditionIsFulfilled()
this.PeformRequest()
}
}
Which is where I am having my problem, RedirectIfConditionIsFulfilled is a private method,
and I can in no way make this method call as such. I could in my overridden function remove this call, but that would
require RedirectIfConditionIsFulfilled to be removed, which would alter the original functionality, which i don't want to do.
So how do i overcome this?
How do i access a private method in a overriden public method?
If you have access to OriginalHandler implementation then make the derived class a nested one:
class A {
private void Foo() { }
protected virtual void Bar() { }
public class B: A {
protected override void Bar() {
Foo(); \\ legal } } }
If you don’t then barring reflection there is no way to access from an external type a private member of another type.
You can't access a private method from an inherited class. (But you know that.)
But your question didn't give any reason why your method shouldn't be protected, which would expose it to inherited classes.
What you're describing is exactly why protected exists.
A nested class will work, but I don't recommend it unless you want every single inherited class that needs the private method to be nested inside the base class. What if some of those inherited classes have their own private methods and even more inherited classes need to access those? You'd have to nest classes inside your nested classes.

C#: Protected Variables inside of a Generic Class can be accessed by a different subclass of that Generic Class. Can I prevent this?

Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
Declare it as readonly in the base class if possible.
Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string[] args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}

Can you add a Derived Class to a list of its base class then call a method of the Derived class from the list of base class in C#

Can you add a Derived Class to a list of its base class then call a method of the Derived class from the list of base class(possibly by casting it back to the Derived class since you know it was originally a Derived class)
public class MySystem
{
public string name;
MySystem(string name)
{
this.name = name;
}
public void Update()
{
//dostuff
}
}
public class PowerSystem : MySystem
{
public int totalPower;
PowerSystem (string name, int power) : base(name)
{
this.totalPower = power;
}
public void Update()
{
base.Update();
//Do other stuff
}
}
void Main()
{
List<MySystem> SystemList = new List<MySystem>();
SystemList.Add(new System("Shields"));
SystemList.Add(new System("Hull"));
Power p = new Power("Power", 10);
SystemList.Add(p);
foreach(MainSystems ms in SystemList)
{
if(ms.name != "Power")
ms.Update();
else
(PowerSystem)ms.Update(); //This doesn't work
}
}
So what I'm trying to do is run the update method for every element in the list, with the exeption of the one I named power and instead run the Power.Update method.
The closest post I have found to answering this is here unfortunately I don't fully understand it.
I'm hoping that the list is holding a reference to PowerSystem p and that somehow I can convert it and access the PowerSystem menthod.
I hope this is clear.
Thanks
PS if you have a better idea for this I'm all ears.
Use polymorphism - mark Update in base class virtual and override it in derived class.
Base classes may define and implement virtual methods, and derived
classes can override them, which means they provide their own
definition and implementation. At run-time, when client code calls the
method, the CLR looks up the run-time type of the object, and invokes
that override of the virtual method. Thus in your source code you can
call a method on a base class, and cause a derived class's version of
the method to be executed.
public class MySystem
{
public string name;
MySystem(string name)
{
this.name = name;
}
public virtual void Update()
{
//dostuff
}
}
public class PowerSystem : MySystem
{
public int totalPower;
PowerSystem (string name, int power) : base(name)
{
this.totalPower = power;
}
public override void Update()
{
base.Update();
//Do other stuff
}
}
Now, PowerSystem.Update() will get called automatically
foreach(MainSystems ms in SystemList)
{
ms.Update();
}
For MySystem instances it will call MySystem.Update, but for PowerSystem instances the override will be called.

Delegates and inheritance in c#

I have a bit of a problem with inheritance of delegates. Delegate as far as i understand is a pointer to a pair: an instance and a method, the thing is this is the method referenced in the creation of the delegate, and not affected by inheritance. So, this won't work:
public class BaseObject {
public delegate void del();
public BaseObject() {
next=Method;
}
public del next;
public void ExecuteNext() {
next();
}
public virtual void Method() {
Debug.Log("BASE");
}
}
public class InheritedObject:BaseObject {
override public void Method() {
Debug.Log("INHERITED");
}
}
...
(new InheritedObject()).ExecuteNext();
Execute runs the base Method(), I want it to run the inherited Method(). I have found some way around, but it is inefficient, distracting and very error prone, anyway here's the current working version that I'd like to get rid of:
class BaseObject {
public delegate void del();
BaseObject() {
next=DoMethod; /// using DoMethod here
}
public del next;
public void ExecuteNext() {
next();
}
public void DoMethod() { /// using DoMethod here
Method();
}
public virtual void Method() {
// do base
}
}
class InheritedObject:BaseObject {
override public void Method() {
// do inherited
}
}
...
(new InheritedObject()).Execute();
This DoMethod aproach works but has many problems,
lots of useless code
error prone when using the class - easy to mistake obj.next=DoMethod with obj.next=Method
error prone when inheriting the class - I have to remember to not to inherit the DoMethod, and lots of virtual and overrides.
Any suggestions how can I do that better? Perhaps some annotation magic that does the DoMethod by itself? I've already thought of dictionaries - they aren't good here, they add even another level of confusion (Mono, .NET 2, Unity3d framework)
You could replace next=DoMethod; with next= ()=>Method(); which is essentially the same, but doesn't require you to define an extra method on your class.
In your first example, you are assigning the result of Method(); to the delegate, so naturally that means that the Method method (ahem) will be executed at that point to assign a value. Ignoring the fact that Method is void (which won't compile).
In the second example, you are assigning a reference to the method (which doesn't have to be an instance method) to the delegate, which allows you to execute the del at a later stage.
The following works for me:
class Program
{
static void Main(string[] args)
{
var baseClass = new BaseObject();
baseClass.Execute();
var derivedClass = new DerivedObject();
derivedClass.Execute();
Console.ReadKey();
}
}
class BaseObject
{
public delegate void SomethingDelegate();
public SomethingDelegate Delegate;
public BaseObject()
{
Delegate += Something;
}
public virtual void Something()
{
Console.WriteLine("Base Class");
}
public void Execute()
{
Delegate();
}
}
class DerivedObject : BaseObject
{
public override void Something()
{
Console.WriteLine("Derived Class");
}
}
In the above example, the fact that the delegate pointer is expressed as a pointer to the Something method (of BaseObject), because the method is virtual, the call is still correctly dispatched to the overriden Something method (of DerivedObject).
Are you not seeing the same behaviour?
No, Execute will run the inherited method. After making some correction to the code I could test it:
public class BaseObject {
public delegate void del();
public BaseObject() {
next = Method;
}
public del next;
public void Execute() {
next();
}
public virtual void Method() {
Console.WriteLine("base");
}
}
public class InheritedObject : BaseObject {
override public void Method() {
Console.WriteLine("inherited");
}
}
Called:
(new InheritedObject()).Execute();
Output:
inherited

Overriding a nested class functions or use delegates?**

I have a base class which has a nested type, inside. There's a function in the outer (base) type which would be overridden by it's children later. In fact this function belongs to the inner type from the OO prespective but still I need it, to be overridden by subtypes of the base class.
Should I use this function as a callback from the inner type or just move it inside the inner type and let's the subtypes to override it from there?
EDIT: Sample code added
class A
{
protected void func() { /* do something */ }
class B { /**/ }
}
// OR
class A
{
class B
{
protected void func() { /* do something */ }
}
}
// Then
class C : A
{
override func() { /**/ }
}
My suggestion is to crate a delegate for the inner type function which is initiated by the constructor of the base class:
internal class BaseClass
{
public BaseClass(Action myAction)
{
this.innerType = new InnerType(myAction);
}
public BaseClass()
{
// When no function delegate is supplied, InnerType should default to
// using its own implementation of the specific function
this.innerType = new InnerType();
}
}
As you see, deriving types can call the base constructor with :base (overridenAction) where they can provide their own implementation of the function right to the innermost type. Of course, you are not obligated to use Action but any delegate you want.
IMO what you are describing looks like The Strategy design pattern. Consider using this pattern. Your code would be much more maintainable as it contains well recognizable pattern. You also can take a look at state design pattern, usually you have to choose between these two, they are closely connected.
In this scenario:
class A
{
class B
{
protected void func() { // do something }
}
}
You cannot derive from class A and override func() in class B.
From your description it seems that A-derived classes should be able to override some function (or functionality) in the inner class B which indicates that you maybe should rethink your design. Either extract B and don't make it an inner class or make the functionality you want to override an explicit dependency via an interface like this:
class A
{
private B _MyB;
public A(ISomeBehaviour behaviour)
{
_MyB = new B(behaviour);
}
}
In anyway if you want to stick with your design then I would not recommend the delegate approach and rather choose the override because with the delegates it makes it harder to add decoration if that is all you need in your child classes.
This is how the outer class can serve as a strategy to the inner service class.
Note that using pattern names such as TemplateMethod and Strategy as real class names is not recommended, use whatever is meaningful in the domain. Same applies to Outer and Inner.
public class Consumer
{
public void Foo()
{
IOuterFoo fooService = new Derived();
fooService.OuterFoo();
}
}
// ...
public interface IOuterFoo
{
void OuterFoo();
}
abstract class Base : Base.IStrategy, IOuterFoo
{
public void OuterFoo() { _service.Foo(); }
private readonly InnerService _service;
protected Base() { _service = new InnerService(this); }
private interface IStrategy { void Foo(); }
private class InnerService
{
private readonly IStrategy _strategy;
public InnerService(IStrategy strategy) { _strategy = strategy; }
public void Foo() { _strategy.Foo(); }
}
void IStrategy.Foo() { TemplateMethodFoo(); }
protected abstract void TemplateMethodFoo();
}
class Derived : Base
{
protected override void TemplateMethodFoo()
{
throw new NotImplementedException();
}
}

Categories