C# Overriding abstract methods (include input parameters) - c#

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

Related

C# Force method implementation in all sub-levels of inheritance and use base implementation

I have a BaseClass, which implements a method to populate itself form a different data structure. SubClasses will add their properties to the base ones. I want all sub-classes and sub-sub...classes to implement their own version of the method and call their parent class to do the same. So this is not just overriding, I want to force the implementation, but each implementation of the method has to be called, not just overridden.
Sort of like:
class BaseClass
{
int id;
virtual void fromDictionary(Dictionary data)
{
id = data["id"];
}
}
class Derived1 : BaseClass
{
string name;
override void fromDictionary(Dictionary data)
{
name = data["name"];
base.fromDictionary(data);
}
}
class Derived2 : Derived1
{
float size;
override void fromDictionary(Dictionary data)
{
size = data["size"];
base.fromDictionary(data);
}
}
Then doing this:
Derived2 object = new Derived2();
object.fromDictionary(dictionary);
Populates all of the object's properties.
I can make the first one virtual and override in the derived ones, but that doesn't force the implementation. And making an abstract base above this base or using an interface wouldn't force ALL levels of inheritance to implement.
The ideal case would be forcing all derived classes to implement their version AND call their parent's version (or even better, have some sort of extension/overriding that automatically calls ALL implementations of the method from the instantiated object's class upwards).
How close to that can I get ?
Seeing why you need this kind of overriding I strongly believe that you should try to move this logic to a constructor because as it looks now:
Derived2 object = new Derived2();
object.fromDictionary(dictionary);
Your object will only be valid if it has a dictionary. So instead of constructing it from a dictionary using a method, you should provide a constructor which receives a dictionary as a parameter:
Derived2 object = new Derived2(dictionary);
Now you have a valid object from the beggining. There are more reasons why you should do this instead of using a method which composes your object, one as you observed is that each subclass will need to call the base method, and having this kind of constructor (assuming that you will not provide a parameterless one) will force the inheritors to call the base one.
Another advantage in using this kind of approach is that you will have a valid object form the beginning instead of making it possible for users of that classes to make invalid objects by forgetting to call the fromDictionary() method.
Thanks for the suggestions everyone, the closest I could get is:
public abstract class DAO
{
public long id { get; set; }
public void fromDictionary(Dictionary<string, object> obj)
{
//Does own part in the method
id = (long)obj["id"];
//Calls most derived implementation
fromDictionaryOperation(obj);
}
//Forces child to implement its part
protected abstract void fromDictionaryOperation(Dictionary<string, object> obj);
}
//Is forced to implement its part, and the base implementation will be executed always
public class Area : DAO
{
public string name { get; set; }
protected override void fromDictionaryOperation(Dictionary<string, object> obj)
{
name = (string)obj["name"];
}
}
//Is NOT forced to implement method, and MUST call base.fromDictionary() for all this to work properly, but is NOT FORCED TO.
public class CircularArea : Area
{
public float radius { get; set; }
protected override void fromDictionaryOperation(Dictionary<string, object> obj)
{
radius = (float)obj["radius"];
base.fromDictionary(obj);
}
}
So all 2nd generation classes will be fine, but subsequent sub-classes wont be forced to implement its part or call the parent implementation. Which means that if in an implementation of a sub-sub-class, the base.fromDictionary() method is not called, then all parent classes implementation, except the first/base class, will be skipped without any compiling warning or error.
To force implementation at all levels, I guess I could put the abstract method in an Interface and make all classes implement the interface, which can't be forced itself, but is as close as I can think of.
If anyone knows a way to completely force ALL of them to implement the same method, that would be top notch.

C# Override virtual function without having to implement another class

I am trying to override a virtual function only for a single defined element (without having to create another class that implements it and then adding a function to override it..).
Example:
public class MyClass
{
public virtual bool ChangeStatus(String status)
{
return false;
}
}
void test()
{
//The following is written as an example of what I am trying to achieve & does not work
MyClass blah = new MyClass()
{
public override bool ChangeStatus(String status)
{
return true;
}
};
}
Any idea how to achieve this?
Thanks.
if you have control over MyClass, you can let the desired method call a delegate which can be replaced for every single object at runtime...
class MyClass
{
public void Func<SomeParameterType,SomeReturnType> myDelegate {get;set;}
public SomeReturnType myFunction(SomeParameterType parameter)
{
if(myDelegate==null)
throw new Exception();
return myDelegate(parameter);
}
}
...
MyClass obj = new MyClass();
SomeParameterType p = new SomeParameterType();
obj.myDelegate = (x)=>new SomeReturnType(x);
SomeReturnType result = obj.myFunction(p);
"virtual" and "override" both are related to INHERITANCE.
1.A virtual method can be redefined. The virtual keyword designates a method that is overridden in derived classes. We can add derived types without modifying the rest of the program. The runtime type of objects thus determines behavior.
2.When you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override.
You cannot override a function without inheriting the class, the whole point of a virtual function is that it can be overridden in the child class.
If your are doing it withing the same class, wouldn't you end up writing a simple method/function for the class ?
So, follow the OOP programming concept, it is designed for simplicity & ease of programming. Instead simply inherit the class and override the function
C# is strictly built on the concept of classes. You cannot create a function/method without a class.
Additionally, virtual/override implies inheritance, so you MUST derive from this class.

Dynamic dispatch to derived class in C#

I'm trying to do the following:
public abstract BaseClass {
public virtual void ReceiveEvent(Event evt)
{
ProcessEvent(evt as dynamic);
}
private void ProcessEvent(object evt)
{
LogManager.Log(#"Received an event that is not being processed!
Dispatch fallback");
}
}
public DerivedClass: BaseClass {
private void ProcessEvent(SpecificEvent evt)
{
LogManager.Log("Processing Event");
}
}
SpecificEvents hit the fallback method instead of the one in the derived class. I use dynamic dispatch within the same class all the time and find it really useful/clean. Will it not work with derived classes as illustrated in the example above?
EDIT:
There seems to be some confusion in the answers. Basically i use the following design all the time:
public class SomeClass{
public void DoSomethingDispatcher(SomeObject obj)
{
ProcessObject(obj as dynamic);
}
private void DoSomething(SomeObjectType1 obj)
{
}
private void DoSomething(SomeObjectType2 obj)
{
}
private void DoSomething(SomeObjectType3 obj)
{
}
private void DoSomething(object obj) //fallback
{
}
}
Works great for when you don't know the exact type beforehand and you don't want to use a big switch statement. Just wondering if this can be implemented with inheritance where the base class holds the fallback method and the derived class holds all the more specific methods.
It's not working for you because even if evt is passed dynamic, ProcessEvent is not declared as virtual. This means that when the call to ProcessEvent is compiled, it is linked to the only implementation of the method that is found in the base class, and the ones in the derived classes will never be executed. Furthermore, you can't simply declare your ProcessEvent as virtual, since the signature will be different in the derived classes.
In order for your code to work as expected you could just override ReceiveEvent in the derived classes leaving it exactly the same:
public override void ReceiveEvent(Event evt)
{
ProcessEvent(evt as dynamic);
}
If you want to manage the unhandled events in the base class, just change the modifier of Process event in the base class to protected (otherwise it can't be executed when called by the overridden version of ReceiveEvents).
If the method is not virtual/abstract in the base class, and the method is not marked as override in the derived class, it will never work.
Also, I dont understand the usage of dynamic here.
What is the type of your "evt" when it hit ProcessEvent ?
You may take a look to Using Type dynamic :
The type is a static type, but an object of type dynamic bypasses
static type checking. In most cases, it functions like it has type
object.
So, evt is not a SpecificEvent.
To get the expected behaviour you should override the virtual method:
public DerivedClass: BaseClass
{
private override void ReceiveEvent(Event evt)
{
// Process your event here.
}
}
With this code, ReceiveEvent in the base class won't be called, thus the fallback ProcessEvent won't be called.
There is no reason to use dynamic.

Force base method call

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..
--edit--
I am mainly curious about overriding methods.
There isn't and shouldn't be anything to do that.
The closest thing I can think of off hand if something like having this in the base class:
public virtual void BeforeFoo(){}
public void Foo()
{
this.BeforeFoo();
//do some stuff
this.AfterFoo();
}
public virtual void AfterFoo(){}
And allow the inheriting class override BeforeFoo and/or AfterFoo
Not in Java. It might be possible in C#, but someone else will have to speak to that.
If I understand correctly you want this:
class A {
public void foo() {
// Do superclass stuff
}
}
class B extends A {
public void foo() {
super.foo();
// Do subclass stuff
}
}
What you can do in Java to enforce usage of the superclass foo is something like:
class A {
public final void foo() {
// Do stuff
...
// Then delegate to subclass
fooImpl();
}
protected abstract void fooImpl();
}
class B extends A {
protected void fooImpl() {
// Do subclass stuff
}
}
It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.
Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.
EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.
The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.
This might be useful for scenarios where the method is invoked by some internal API.
i.e. where Foo() is not designed to be invoked directly:
public abstract class ExampleBase {
private bool _baseInvoked;
internal protected virtual void Foo() {
_baseInvoked = true;
// IMPORTANT: This must always be executed!
}
internal void InvokeFoo() {
Foo();
if (!_baseInvoked)
throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
}
}
Works:
public class ExampleA : ExampleBase {
protected override void Foo() {
base.Foo();
}
}
Yells:
public class ExampleB : ExampleBase {
protected override void Foo() {
}
}
I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...
public abstract class Animal
{
protected abstract void Hello();
public void SayHello()
{
//Do some mandatory thing
Console.WriteLine("something mandatory");
Hello();
Console.WriteLine();
}
}
public class Dog : Animal
{
protected override void Hello()
{
Console.WriteLine("woof");
}
}
public class Cat : Animal
{
protected override void Hello()
{
Console.WriteLine("meow");
}
}
Example usage:
static void Main(string[] args)
{
var animals = new List<Animal>()
{
new Cat(),
new Dog(),
new Dog(),
new Dog()
};
animals.ForEach(animal => animal.SayHello());
Console.ReadKey();
}
Which produces:
You may want to look at this (call super antipatern) http://en.wikipedia.org/wiki/Call_super
If I understand correctly you want to enforce that your base class behaviour is not overriden, but still be able to extend it, then I'd use the template method design pattern and in C# don't include the virtual keyword in the method definition.
No. It is not possible. If you have to have a function that does some pre or post action do something like this:
internal class Class1
{
internal virtual void SomeFunc()
{
// no guarantee this code will run
}
internal void MakeSureICanDoSomething()
{
// do pre stuff I have to do
ThisCodeMayNotRun();
// do post stuff I have to do
}
internal virtual void ThisCodeMayNotRun()
{
// this code may or may not run depending on
// the derived class
}
}
I didn't read ALL the replies here; however, I was considering the same question. After reviewing what I REALLY wanted to do, it seemed to me that if I want to FORCE the call to the base method that I should not have declared the base method virtual (override-able) in the first place.
Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.
Don't think there's any feasible solution built-in. I'm sure there's separate code analysis tools that can do that, though.
EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.
In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.
class Parent {
protected Parent(int id) {
}
}
class Child : Parent {
// Does not compile
public Child() {}
// Also does not compile
public Child(int id) { }
// Compiles
public Child() :base(42) {}
}
In java, the compiler can only enforce this in the case of Constructors.
A constructor must be called all the way up the inheritance chain .. ie if Dog extends Animal extends Thing, the constructor for Dog must call a constructor for Animal must call a constructor for Thing.
This is not the case for regular methods, where the programmer must explicitly call a super implementation if necessary.
The only way to enforce some base implementation code to be run is to split override-able code into a separate method call:
public class Super
{
public final void doIt()
{
// cannot be overridden
doItSub();
}
protected void doItSub()
{
// override this
}
}
public class Sub extends Super
{
protected void doItSub()
{
// override logic
}
}
I stumbled on to this post and didn't necessarily like any particular answer, so I figured I would provide my own ...
There is no way in C# to enforce that the base method is called. Therefore coding as such is considered an anti-pattern since a follow-up developer may not realize they must call the base method else the class will be in an incomplete or bad state.
However, I have found circumstances where this type of functionality is required and can be fulfilled accordingly. Usually the derived class needs a resource of the base class. In order to get the resource, which normally might be exposed via a property, it is instead exposed via a method. The derived class has no choice but to call the method to get the resource, therefore ensuring that the base class method is executed.
The next logical question one might ask is why not put it in the constructor instead? The reason is that it may be an order of operations issue. At the time the class is constructed, there may be some inputs still missing.
Does this get away from the question? Yes and no. Yes, it does force the derived class to call a particular base class method. No, it does not do this with the override keyword. Could this be helpful to an individual looking for an answer to this post, maybe.
I'm not preaching this as gospel, and if individuals see a downside to this approach, I would love to hear about it.
On the Android platform there is a Java annotation called 'CallSuper' that enforces the calling of the base method at compile time (although this check is quite basic). Probably the same type of mechanism can be easily implemented in Java in the same exact way. https://developer.android.com/reference/androidx/annotation/CallSuper

C# - using polymorphism in classes I didn't write

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.

Categories

Resources