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.
Related
Good day,
I have a base class with a virtual method that needs to be overridden per implementation, but I would like to call the base method first before overriding.
Is there a way to accomplish this without having to actually call the method.
public class Base
{
public virtual void Method()
{
//doing some stuff here
}
}
public class Parent : Base
{
public override void Method()
{
base.Method() //need to be called ALWAYS
//then I do my thing
}
}
I cannot always rely that the base.Method() will be called in the override, so I would like to enforce it somehow. This might be a design pattern of some kind, any approach to accomplish the result will do.
One way is to define a public method in the base class, which calls another method that can be (or must be) overridden:
public class Base
{
public void Method()
{
// Do some preparatory stuff here, then call a method that might be overridden
MethodImpl()
}
protected virtual void MethodImpl() // Not accessible apart from child classes
{
}
}
public class Parent : Base
{
protected override void MethodImpl()
{
// ToDo - implement to taste
}
}
You can use the decorator design pattern, applying this pattern you can attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality:
public abstract class Component
{
public abstract void Operation();
}
public class ConcreteComponent1 : Component
{
public override void Operation()
{
//logic
}
}
public abstract class ComponentDecorator : Component
{
protected readonly Component Component;
protected ComponentDecorator(Component component)
{
Component = component;
}
public override void Operation()
{
if(Component != null)
Component.Operation();
}
}
public class ConcreteDecorator : ComponentDecorator
{
public ConcreteDecorator(Component component) : base(component)
{
}
public override void Operation()
{
base.Operation();
Console.WriteLine("Extend functionality");
}
}
Hope this helps!
I would like to ask what are the risks of having something as follows:
abstract public class HtmlTemplateBuilder
{
HtmlSource source;
protected HtmlTemplateBuilder()
{
LoadTemplates();
}
public abstract void LoadTemplates();
}
The risk is if a derived class derives from the derived class:
DerivedClass2 -> #DerivedClass1 -> HtmlTemplateBuilder
This can be solved by sealing #DerviedClass1, but are there any more risks or better practices for implementing this functionality?
Thanks
The situation in which this pattern bit me is as follows: at some later stage you want to add a specialized HtmlTemplateBuilder, which can load different templates based on some criteria unknown to the class itself (maybe you decide you want some cool templates on a specific day of the year). That is:
public class SpecialHtmlTemplateBuilder : HtmlTemplateBuilder
{
private bool someCondition;
public override void LoadTemplates()
{
if (someCondition)
{
LoadTemplatesSet1();
}
else
{
LoadTemplatesSet2();
}
}
}
But how are you going to pass someCondition to the class? The following won't work:
public class SpecialHtmlTemplateBuilder : HtmlTemplateBuilder
{
private bool someCondition;
public SpecialHtmlTemplateBuilder (bool someCondition)
{
this.someCondition = someCondition;
}
// ...
}
because the assignment of this.someCondition will be done after calling the base constructor, i.e., after LoadTemplates() is called. Note that sealing derived classes does not solve this problem.
The way to solve this is as #Rahul Misra described: add an explicit Initialize method and call that after the constructor.
Have a look at this link which explains the perils with simple easy to understand examples
https://blogs.msmvps.com/peterritchie/2012/04/25/virtual-method-call-from-constructor-what-could-go-wrong/
I would remove the call to LoadTemplates from constructor and call Initialise on it when the templates actually need to be loaded and used.
abstract public class HtmlTemplateBuilder
{
HtmlSource source;
object locker = new object();
private bool initialised;
protected HtmlTemplateBuilder()
{
}
protected void Initialise()
{
lock (locker)
{
if(initialised)
{
LoadTemplates();
initialised = true;
}
}
}
public abstract void LoadTemplates();
}
As you can see in the code below, the DoStuff() method is getting called before the Init() one during the construction of a Child object.
I'm in a situation where I have numerous child classes. Therefore, repeating a call to the DoStuff() method directly after Init() in the constructor of each child wouldn't be an elegant solution.
Is there any way I could create some kind of post constructor in the parent class that would be executed after the child's constructor? This way, I could call to the DoStuff() method there.
If you have any other design idea which could solve my problem, I'd like to hear it too!
abstract class Parent
{
public Parent()
{
DoStuff();
}
protected abstract void DoStuff();
}
class Child : Parent
{
public Child()
// DoStuff is called here before Init
// because of the preconstruction
{
Init();
}
private void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
If you have a complex logic for constructing your objects then consider FactoryMethod pattern.
In your case I would implement it as a simple
public static Parent Construct(someParam)
method that takes some parameter and based on it decides which child class to instantiate.
You can remove your DoStuff() method call from the constructor and call it inside Construct() on the new instance.
Also, you should avoid virtual/abstract method calls in the constructors. See this question for more details: Virtual member call in a constructor
Let me introduce a general solution using some C# features. Note that this solution does not require you to use a factory pattern or invoke anything after constructing the object, and it works on any class with just implementing an interface with a single method.
First we declare an interface that our classes will have to implement:
public interface IInitialize {
void OnInitialize();
}
Next we add a static extension class for this interface, and add the Initialize method:
public static class InitializeExtensions
{
public static void Initialize<T>(this T obj) where T: IInitialize
{
if (obj.GetType() == typeof(T))
obj.OnInitialize();
}
}
Now, if we need a class and all of its descendants to call an initializer right after the object is fully constructed, all we need to do is implement IInitialize and append a line in the constructor:
public class Parent : IInitialize
{
public virtual void OnInitialize()
{
Console.WriteLine("Parent");
}
public Parent()
{
this.Initialize();
}
}
public class Child : Parent
{
public Child()
{
this.Initialize();
}
public override void OnInitialize()
{
Console.WriteLine("Child");
}
}
public class GrandChild : Child
{
public GrandChild()
{
this.Initialize();
}
public override void OnInitialize()
{
Console.WriteLine("GrandChild");
}
}
The trick is that when a derived class calls the extension method Initialize, that will suppress any calls not made from the actual class.
How about this:
abstract class Parent
{
public Parent()
{
Init();
DoStuff();
}
protected abstract void DoStuff();
protected abstract void Init();
}
class Child : Parent
{
public Child()
{
}
protected override void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
As others have mentioned, you should use a Factory Pattern.
public class Parent
{
public Parent()
{
}
public virtual void PostConstructor()
{
}
}
public class Child : Parent
{
public override void PostConstructor()
{
base.PostConstructor();
// Your code here
}
}
public void FactoryMethod<T>() where T : Parent
{
T newobject = new T();
newobject.PostConstructor();
}
I would strongly suggest use Factory like a pattern.
If it's possible:
1. Push all your childs and abstract class into separate assembly.
2. Declare ctors of childs like internal methods, so no one out of that assembly is can construct them just by calling ctor.
3. Implement the Factory class to construct for caller specified objects type, which obviuoly will forse calling of abstract DoStuff() method after actual creation of anobject, but before returning it to caller.
Good thing about this is that: It will give you also additional level of abstraction, so if in the future you will need some more functions call or any other type of logical complexity, what you will need, is just add them into your Factory class.
That is.
Regards
In WPF applications, you can postpone the invokation of DoStuff() with the help of Dispatcher:
abstract class Parent
{
public Parent()
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(this.DoStuff));
}
private void DoStuff()
{
// stuff, could also be abstract or virtual
}
}
However, it is not guaranteed that DoStuff() will be called immediately after the constructor.
Correction: As per this answer, you can't determine when the base class's constructor is invoked during construction of the subclass.
E.g. This doesn't work:
public Child()
// DoStuff is called here after Init
// because of the overridden default constructor
{
Init();
base();
}
So, yes, as others have noted, if sequence of events matters, then the base class needs to be able to accommodate that by declaring abstract methods in order, or (better yet) by having the child class's implementation of DoStuff represent the sequence of events:
protected override void DoStuff()
{
Init();
base.DoStuff();
}
DoStuff is abstract. Just call Init from the top of DoStuff.
class MyBase
{
public MyBase()
{
//... do something
// finally call post constructor
PostConstructor<MyBase>();
}
public void PostConstructor<T>( )
{
// check
if (GetType() != typeof(T))
return;
// info
System.Diagnostics.Debug.WriteLine("Post constructor : " + GetType());
}
}
class MyChild : MyBase
{
public MyChild()
{
// ... do something
// ... call post constructor
PostConstructor<MyChild>();
}
}
How about...
public MyClass()
{
Dispatcher.UIThread.Post(RunAfterConstructor);
}
I also tried with Task.Run but that didn't work reliably.
Rather than using an abstract method, which would require you to implement the method in all descendant classes, you might try:
public class Parent
{
public Parent()
{
PostConstructor();
}
protected virtual void PostConstructor()
{
}
}
public class Child : Parent
{
protected override void PostConstructor()
{
base.PostConstructor();
/// do whatever initialization here that you require
}
}
public class ChildWithoutOverride
{
/// not necessary to override PostConstructor
}
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();
}
}
I have this situation that when AbstractMethod method is invoked from ImplementClass I want to enforce that MustBeCalled method in the AbstractClass is invoked. I’ve never come across this situation before. Thank you!
public abstract class AbstractClass
{
public abstract void AbstractMethod();
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
}
public class ImplementClass : AbstractClass
{
public override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
An option would be to have the Abstract class do the calling in this manner. Otherwise, there is no way in c# to require an inherited class to implement a method in a certain way.
public abstract class AbstractClass
{
public void PerformThisFunction()
{
MustBeCalled();
AbstractMethod();
}
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
//could also be public if desired
protected abstract void AbstractMethod();
}
public class ImplementClass : AbstractClass
{
protected override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
Doing this creates the desired public facing method in the abstract class, giving the abstract class over how and in what order things are called, while still allowing the concrete class to provide needed functionality.
How about
public abstract class AbstractClass
{
public void AbstractMethod()
{
MustBeCalled();
InternalAbstractMethod();
}
protected abstract void InternalAbstractMethod();
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
}
public class ImplementClass : AbstractClass
{
protected override void InternalAbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
Why can't you just call the method in the AbstractMethod() of Implement class?
One thing the preceding solutions ignore is that ImplementClass can redefine MethodToBeCalled and not call MustBeCalled -
public abstract class AbstractClass
{
public abstract void AbstractMethod();
private void MustBeCalled()
{
//will be invoked by MethodToBeCalled();
Console.WriteLine("AbstractClass.MustBeCalled");
}
public void MethodToBeCalled()
{
MustBeCalled();
AbstractMethod();
}
}
public class ImplementClass : AbstractClass
{
public override void AbstractMethod()
{
Console.WriteLine("ImplementClass.InternalAbstractMethod");
}
public new void MethodToBeCalled() {
AbstractMethod();
}
}
If only C# allowed non-overridden methods to be sealed - like Java's final keyword!
The only way I can think of to overcome this is to use delegation rather than inheritance, because classes can be defined as sealed. And I'm using a namespace and the "internal" access modifier to prevent providing a new implementation on implementing classes. Also, the method to override must be defined as protected, otherwise users could call it directly.
namespace Something
{
public sealed class OuterClass
{
private AbstractInnerClass inner;
public OuterClass(AbstractInnerClass inner)
{
this.inner = inner;
}
public void MethodToBeCalled()
{
MustBeCalled();
inner.CalledByOuter();
}
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
System.Console.WriteLine("OuterClass.MustBeCalled");
}
}
public abstract class AbstractInnerClass
{
internal void CalledByOuter()
{
AbstractMethod();
}
protected abstract void AbstractMethod();
}
}
public class ImplementInnerClass : Something.AbstractInnerClass
{
protected override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
System.Console.WriteLine("ImplementInnerClass.AbstractMethod");
}
public new void CalledByOuter()
{
System.Console.WriteLine("doesn't work");
}
}