I want to write a framework which needs to implement a few functions. Now I need to access the base class functions from the framework, which does not work.
I need to inherit form a given class "Master"
public class MyClass : Master
{
protected override void Initialize() {
FunctionInMaster();
VariableInMaster = true;
}
}
Now I simply want to create a class that can be derived and implements Master functions.
public class MyFrameworkClass
{
// framework override
public void whatever()
{
FunctionInMaster();
VariableInMaster = true;
}
}
public class MyClass : Master
{
protected override void Initialize() {
whatever();
FunctionInMaster();
VariableInMaster = true;
}
}
How do I do that without instantiating "MyFrameworkClass" and passing a pointer of "this" to MyFrameworkClass?
You can never have multiple inheritance in C# (and it's a very good thing, multiple inheritance is a nightmare), but you can invoke methods from other classes, or even have some composition.
public static class MyFrameworkClass
{
// framework override
public static void whatever(Master master)
{
master.FunctionInMaster();
master.VariableInMaster = true;
}
}
public class MyClass : Master
{
protected override void Initialize()
{
MyFrameWorkClass.whatever(this);
FunctionInMaster();
VariableInMaster = true;
}
}
Don't try to do too many things with inheritance. Inheritance is a powerful tool, but not an universal one. Often composition is better suited to tackle a specific problem.
You could also have multiple levels of inheritance, if you need to access protected methods and you know you will reuse this code in other derived classes.
public class MyFrameworkClass : Master
{
// framework override
protected void whatever()
{
FunctionInMaster();
VariableInMaster = true;
}
}
public class MyClass : MyFrameworkClass
{
protected override void Initialize()
{
whatever();
FunctionInMaster();
VariableInMaster = true;
}
}
Although you could change inheritance to be Master -> MyFrameworks -> MyClass, that is less advisable. Is the intention to make sure deriving classes implement specific methods - in that case consider adding abstract methods to Master. If you are unable to alter Master, you can change MyFrameworks to be an interface rather than a class. MyClass can inherit multiple interfaces, but only one class.
I need to access the base class [instance] functions from the framework
To call instance methods you need an instance. There are three ways to do that:
Inherit form the class and use this - you have already stated that you can't do this.
Accept an instance of the base class and call methods on it - you have stated that you don't want to do this.
Create an instance of the class and call methods on it.
Now static methods are different - you do not need an instance, but they can only use static fields, which would be shared across all instances of the class. Since you use a non-static property in the base class, it's safe to assume that static is not an option, so you're stuck with one of the three options above.
Related
I'm sorry if these types of questions aren't allowed.
I have a simple base for something similar to plugins.
Here's my example
class Plugin{
private bool _Enabled;
public bool Enabled{
get{
return _Enabled;
}
set{
_Enabled = value;
if(value)
MyExecutionHandler += Run;
}
}
public virtual void Run(object source, System.EventArgs args)
{
if(!Enabled)
return;
}
}
Now currently I'm doing something like this:
class CustomPlugin : Plugin{
public override void Run(object source, System.EventArgs args)
{
base.Run(source, args);
}
}
First of all is the logic behind this correct?
Secondly can I force them to implement the Run function from the partial class or do I need to create an interface for that?
You can define an abstract class with "default" behavior by declaring a method as virtual and overriding it in derived classes.
A derived class is not forced to override a virtual method in an abstract base class. If the method is not overridden, the behavior defined in the abstract class is used. Overriding the method can be used to replace the behavior entirely, or implement additional functionality (on top of calling base.MethodName()).
Unless I've misunderstood your question, this pattern should work for your scenario.
dotnetfiddle link: https://dotnetfiddle.net/7JQQ6I
Abstract base class:
public abstract class Plugin
{
public virtual string Output()
{
return "Default";
}
}
A derived class that uses the default implementation, and one that overrides it:
public class BoringPlugin : Plugin
{
public override string Output()
{
return base.Output();
}
}
public class ExcitingPlugin : Plugin
{
public override string Output()
{
return "No boring defaults here!";
}
}
Test result:
public static void Main()
{
var boring = new BoringPlugin();
Console.WriteLine(boring.Output());
var exciting = new ExcitingPlugin();
Console.WriteLine(exciting.Output());
}
Default
No boring defaults here!
This is not the correct way to use the partial keyword. The partial keyword merely allows you to spread the definition of a class into multiple source files. It isn't something you use to describe the architecture of your program. You would use it to split the definition into multiple files, something like this:
Plugin1.cs
partial class Plugin{
private bool _Enabled;
public bool Enabled{
get{
return _Enabled;
}
set{
_Enabled = value;
if(value)
MyExecutionHandler += Run;
}
}
}
Plugin2.cs
partial class Plugin {
public virtual void Run(object source, System.EventArgs args)
{
if(!Enabled)
return;
}
}
But this isn't helpful to you, and you should forget about the partial keyword (for now). You seem to be struggling with concepts related to object-oriented programming. The partial keyword has nothing to do with that, so don't worry about it.
If you want classes which inherit from Plugin to be 'forced' to implement the Run method, you should use an abstract method. HOWEVER, as you will read in that link, if you use an abstract method, you will not be able to define the 'default' behavior which you are currently defining in the body of the run method.
If you want classes which inherit from Plugin to be forced to define ADDITIONAL behavior, you can't really do that easily just using concepts like abstract classes / methods / interfaces. You will find it easier to compromise, and allow classes which inherit from plugin to 'just' have the default behavior of the Run method as described in your Plugin base class.
You will probably find this compromise acceptable. I think you will find that forcing classes which inherit from Plugin to do additional things in the Run method doesn't buy you anything. The behavior in the base Run method should still be considered a 'correct', if minimal / useless 'Run' of any type of derived Plugin.
I can't speak to the logic of your program, it isn't clear what you intend for these Plugins to do, but hopefully this will help you figure out exactly what you want to do, and how to do it.
I have no practical experience with OO design, thus I am hesitant as to the solution I adopted for the following problem:
I have to process network text files that come from N different sources, in different formats - with the processing consisting in the classical reading, computations, and insertion into database.
The solution I devised was to create a class that defines all functionalities/behaviors that are core/file-format-independent, and create derived classes from the latter where each contain the appropriate format-reading logic, according to the file-type the given class handles.
All files are read via File.ReadAllLines(), what differs is mapping fields from the file into the main object's variables. So I did this by defining an event in the base class, that is called after File.ReadAllLines(), and all derived classes attach their mapping logic to the inherited event.
But I understand this solution is not correct design-wise. First of all, there is no meaning in instantiating the base class, so it should be abstract. The reason I did not make it abstract is that the construction code for all the derived objects is the same, so I defined it as the base constructor. Should I declare an "Initialize" method in the abstract class and simply call it in every derived class's constructor? (looks weird...)
Perhaps interfaces? I don't see how using an interface would give me any benefits here, besides it will not solve this "constructor" problem...
What is the correct solution?
Code demonstration of my scenario:
public delegate void myDelegate(object parameter);
class Base
{
#region Attributes
...
#endregion
public Base(object p)
{
//initialization code
...
}
#region Methods
protected void m1() { }
protected void m2() { }
...
#endregion
public event myDelegate myEvent;
}
class Child1
{
public Child1(object o) : base(o)
{
this.myEvent += new myDelegate(ChildMethod);
}
public void ChildMethod(object o)
{
...
}
}
First of all, there is no meaning in instantiating the base class, so it should be abstract. The reason I did not make it abstract is that the construction code for all the derived objects is the same, so I defined it as the base constructor.
You still can make the base class abstract yet have common constructor logic in the base class constructor. I see in your code you've already figured out how to call the base class constructor; that's all you need to do.
abstract class Base {
public Base(object o) { }
public abstract void M();
}
class Derived : Base {
public Derived(object o) : base(o) { }
public override void M() { }
}
It is possible in C# do something like this
public absctract class ImportBase()
{
public abstract void CreateDocument();
}
public class UsingOne : ImportBase
{
public override bool CreateDocument(string name)
{
return null;
}
}
I want have some Base class, which only have some methods,but in derived class i need change inputs parameters and inside of method.
You're not overriding the method. The point of having an abstract (or virtual) method is that given any ImportBase, I should be able to call
importBase.CreateDocument();
That's clearly not the case with UsingOne, as it needs more information. So you're really trying to tie your caller to UsingOne, not just ImportBase - at which point you've lost the benefits of polymorphism.
To override a method, the implementation has to have the same signature, basically.
Probably you want to minimize the duplicate code on your derived classes. Basically it's not possible to have an override of a different signature but surely you can refactor your code where you can keep the possible duplicate code in the base class and use it on your derived classes.
public absctract class ImportBase()
{
//Making this protected here
protected virtual void CreateDocument()
{
//Your CreateDocument code
};
}
public class UsingOne : ImportBase
{
private override void CreateDocument()
{
// Override this if you have different CreateDocument for your different
// for different derived class.
}
public bool CreateDocument(string name)
{
// Do whatever you need to do with name parameter.
base.CreateDocument();
// Do whatever you need to do with name parameter.
return true; // return false;
}
}
You can create instance of UsingOne and invoke CreateDocument(string name)
nope. signature must be same on the derived class. i suggest to use builder pattern.
http://en.wikipedia.org/wiki/Builder_pattern
What are all the difference between an abstract class, and a class with only protected constructor(s)? They seem to be pretty similar to me, in that you can't instantiate either one.
EDIT:
How would you create an instance in a derived class, with a base class with a protected constructor? For instance:
public class ProtectedConstructor
{
protected ProtectedConstructor()
{
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor(); // this is fine
}
}
public class DerivedClass : ProtectedConstructor
{
public void createInstance()
{
ProtectedConstructor p = new ProtectedConstructor(); // doesn't compile
}
public static ProtectedConstructor getInstance()
{
return new ProtectedConstructor(); // doesn't compile
}
}
You can instantiate a class with protected constructors from within the class itself - in a static constructor or static method. This can be used to implement a singleton, or a factory-type thing.
An abstract class cannot be instantiated at all - the intent is that one or more child classes will complete the implementation, and those classes will get instantiated
Edit:
if you call ProtectedConstructor.GetInstance(); instead of new ProtectedConstructor();, it works. Maybe protected constructors can't be called this way? But protected methods certainly can.
Here is an interesting article on the topic.
Most of the time, there is little practical difference, as both are only able to be generated via a subclass.
However, marking a class abstract has two benefits:
With protected constructors, it's still possible to create an instance of the class in two ways. You can use Activator.CreateInstance with BindingFlags.NonPublic, or you can use a factory method defined in the class (or a subclass) to create an instance of the class. A class marked abstract, however, cannot be created.
You are making your intention more clear by marking the class abstract. Personally, I find this the most compelling reason to do so.
From an outside , black-box perspective, yes they are similar in that you cannot instantiate either one. However, you can never instantiate an abstract class, where you can construct a class with only protected constructors from within the class itself, or from an inheritor.
An abstract class can have abstract methods; methods that consist only of the method signature, but no body, that child classes must implement.
Seriously, not one person mentioned that yet?
Your example is flawed because in the getInstance case because you construct a ProtectedConstructor class and expect to down cast it as a DerivedClass. Instead you need a slightly more complete implementation where the derived class has a constrcutor:
public class ProtectedConstructor
{
protected ProtectedConstructor(string arg)
{
// do something with arg
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor("test");
}
}
public class DerivedClass : ProtectedConstructor
{
protected DerivedClass(string arg) : base(arg)
{
}
public void createInstance()
{
DerivedClass p = new DerivedClass("test");
}
public static DerivedClass getInstance()
{
return new DerivedClass("test");
}
}
Regardless the major difference usage of abstract classes is to define abstract methods that subclasses must implement but you don't want to provide a default implementation for. For example suppose you have some kind of Thread class that has a Run method. You want to ensure that every call to Run first setups up some logging then does the real work of the thread and then stops logging. You could write an abstract Thread class like this:
public abstract Thread
{
protected Thread()
{
}
public void Run()
{
LogStart();
DoRun();
LogEnd();
}
protected abstract DoRun();
private void LogStart()
{
Console.Write("Starting Thread Run");
}
private void LogEnd()
{
Console.Write("Ending Thread Run");
}
}
public class HelloWorldThread : Thread
{
public HelloWorldThread()
{
}
protected override DoRun()
{
Console.Write("Hello World");
}
}
Another thing to consider, that I didn't see other people mention, is that your code may be maintained in the future. If the maintainer adds a public constructor to a class, then it can be instantiated. This might break your design, so you should prevent it (or design to accommodate it).
To prevent other people from making these kinds of changes, you can comment your code. Or, as other people said, use "abstract" to explicitly document your intent.
Well, the first difference that comes to mind is that an abstract class can not be instantiated, but a class with protected constructors could be instantiated throw another public method.
A common example of this might be something like the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern
if you inherit an abstract class from another abstract class, you do not have to satisfy abstract methods, but you do with a normal class with protected ctors. Examples
public abstract class Parent
{
protected abstract void AMethod();
}
public abstract class Child: Parent
{
// does not implement AMethod, and that's ok
}
public class Child2: Parent
{
// does not implement AMethod, and that will cause a compile error
}
If your intent is to only allow static uses of the class (i.e. not to use it as a pure base class) then you should use the static keyword instead; the CLR will prevent instances of the class being created via any method including Reflection (AFAIK).
What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.