Override method from instance of the class - c#

I have a merly simple question, but seems cant find an answer for it, I want to know if its possible to override a method from a instance class structore would look like this:
public class A : baseA
{
public virtual void methodA()
{
}
}
public class B : baseB
{
public void method B()
{
var ClassA = new A();
}
/* Now Is there some sort of overide like */
public override methodA()
{
//Do stuff
}
}
And those classes do not inherit from each other, to make it more difficult.
Now if this sort of construction is possible in c#?

No. You cannot override a class's behavior if you don't inherit from it.
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Class B must inherit from class A in order to do so.
public class A
{
public virtual void methodA()
{
}
}
public class B : A
{
public void methodB()
{
var ClassA = new A();
}
public override void methodA()
{
//Do stuff
}
}
Check MSDN for more details:
An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method

Related

C# How to call a derived methods?

I have a situation where I want to call only one method and have all the methods its derived from called also.
public class Base
{
public virtual void Method()
{
// Do something
}
}
public class Derived1 : Base
{
public override void Method()
{
base.Method();
// Do something
}
}
public class Derived2 : Derived1
{
public override void Method()
{
base.Method();
// Do something
}
}
I want to only call Derived2.Method() and have all the Methods() called that it derives from
The issue with the way I currently have it set up is that Derived1.Method() never gets called.
Is there a way to make the called method call all the previous instances of it in a derived class?

Can we change grand parent class's method definitions?

I was working on a certain problem and found some interesting problem inside.
Let me explain with an example (C# code)
public class A: IA
{
protected abstract void Append(LoggingEvent loggingEvent)
{
//Some definition
}
}
public class B: A
{
protected override void Append(LoggingEvent loggingEvent)
{
//override definition
}
}
public class MyClass: B
{
//Here I want to change the definition of Append method.
}
Class A and B are of a certain library and I don't have any control to change those classes.
Since none of the methods in the hierarchy here are sealed, you can just continue overriding the method yourself:
public class MyClass: B
{
protected override void Append(LoggingEvent loggingEvent)
{
// New logic goes here...
}
}
I have shared the solution below based as per my research, but made few following changes to the code you shared based on my perception, since the code in the question is not valid at few occasions.
Added an empty Interface IA, as Class A is not implementing any public method.
Defined Class A as abstract, as any non-abstract class cannot define a abstract method.
Removed the body for Append method inside Class A, as a abstract method cannot have a body.
public interface IA
{
}
public abstract class A : IA
{
protected abstract void Append();
}
public class B : A
{
protected override void Append()
{
//override definition
}
}
public class MyClass : B
{
//Here I want to change the definition of Append method.
//You can do is hide the method by creating a new method with the same name
public new void Append() { }
}
Answer : You cannot override a non-virtual method. The closest thing you can do is hide the method by creating a new method with the same name but this is not advisable as it breaks good design principles.
But even hiding a method won't give you execution time polymorphic dispatch of method calls like a true virtual method call would.

Define base class constructor methods in derived classes

I am trying to create a comprehensive abstract BaseClass that defines the way in which all derived classes are created, but allows derived classes to specialize/aggregate the fields and methods used in the creation process. Here is a simplified example:
public abstract class BaseClass
{
public List<String> list;
public BaseClass()
{
defineList();
optionalDoSomething();
doSomething();
}
protected void defineList()
{
list = new List<String>();
}
protected void doSomething()
{
// do something w/ list here
}
protected void optionalDoSomething() {}
}
public class DerivedClass : BaseClass
{
protected void defineList()
{
base.defineList();
list.Add("something");
}
public DerivedClass() : base() { }
}
public class SecondDerivedClass : DerivedClass
{
protected void defineList()
{
base.defineList();
list.Add("somethingElse");
}
protected void optionalDoSomething()
{
// do something special
}
public SecondDerivedClass() : base() { }
}
This would free all derived classes from having to recreate the same initialization logic, and each derived class would only need to "overwrite" the necessary fields and methods used in the create process (and possibly elsewhere in the class).
The problem:
I cannot mark BaseClass' methods as virtual since you cannot call virtual methods in a base constructor (in any case, I would not want to use virtual methods since, for example, I would not want DerivedClass to use SecondDerivedClass' defineList method).
I can mark them abstract, but then I would not be able to put "default implementations" in BaseClass and each derived class would have to replicate/implement those defaults. Also, SecondDerived class would still need a way to "override" the implementations of DerivedClass.
It does not work to simply use the new key word "hide" less derived class' methods.
What is the correct way to obtain this pattern?
TLDR: as per my comment below:
If BaseClass is an abstract class with method A, and DerivedClass is a class derived from BaseClass (not necessarily a direct child of BaseClass), then calling A in BaseClass' constructor should call A() in every class in the inheritance hierarchy up to and including DerivedClass (but no further). We can assume that A (forced to be) defined on every intermediate class.
I think that you should refer to template-method-design-pattern
Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm's structure.
you can try something similar to this
abstract class AbstractClass
{
public List<String> list;
public abstract void PrimitiveOperation1();
public void TemplateMethod()
{
//initialize code that each class should perform
PrimitiveOperation1();
}
}
class DerivedClass: AbstractClass
{
public override void PrimitiveOperation1()
{
list.Add("something");
}
}
usage
AbstractClass abstractClass1 = new DerivedClass();
abstractClass1.TemplateMethod();
Try this solution, the implementation is implemented with protected virtual methods, so its not visible from the outside and not required in derived classes:
public abstract class BaseClass
{
public List<String> List { get; protected set; }
protected BaseClass()
{
defineList();
optionalDoSomething();
doSomething();
}
protected void defineList()
{
// default implementation here
List = new List<String>();
internalDefineList();
}
protected void doSomething()
{
// default implementation here
internalDoSomething();
}
protected void optionalDoSomething()
{
// default implementation here
internalOptionalSomething();
}
protected virtual void internalDefineList()
{
}
protected virtual void internalDoSomething()
{
}
protected virtual void internalOptionalSomething()
{
}
}
public class DerivedClass : BaseClass
{
protected override void internalDefineList()
{
var list = List;
}
protected override void internalDoSomething()
{
}
// this method is not required
/*
protected override void internalOptionalSomething()
{
}
*/
}
One way to achieve what you want is to add an explicit Initialize method to the base class and do the initializaiton logic there, e.g:
public abstract class BaseClass
{
public List<String> list;
public BaseClass()
{
}
public void Initialize()
{
defineList();
optionalDoSomething();
doSomething();
}
}

Is it possible to override a base method with a more specific (by return type) method?

I have classes like this.
public class Base{
public virtual Base Clone(){ ...... }
}
public class Derived:Base{
public Derived Clone(){ ...... }
private override Base Clone(){ return Clone(); }
}
This code, of course, gives me some compile errors, one saying there are two Clone() methods in Derived class and the other saying that overriding method must be in the same accessibility level as the overridden one.
Now, since the Derived.Clone() method which overrides Base.Clone() is never needed directly, I'd like to hide it with the more specific Derived.Clone() method which returns a Derived object. I know this can be done in C# with interfaces, but is it possible to do the same with classes?
Not in the way you show. A common approach is to introduce an extra method for the implementation:
public class Base
{
public Base Clone() { return CloneImpl(); }
protected virtual Base CloneImpl() { ... }
}
public class Derived : Base
{
public new Derived Clone() { ... }
protected override Base CloneImpl() { return Clone(); }
}
This then satisfies all expectations of polymorphism, substitution, etc.
To go a little further on the answer of Marc which is in basis what you need, I would change the signature of the internal method:
public class Base
{
public Base Clone()
{
Base b = new Base();
CloneImpl(b);
return b;
}
protected virtual void CloneImpl(Base b) { ... }
}
public class Derived : Base
{
public new Derived Clone()
{
Derived d = new Derived();
this.CloneImpl(d);
return d;
}
protected override void CloneImpl(Base b)
{
Derived d = b as Derived;
...
base.CloneImpl(d);
}
}
In this way the internal method can do the work for the type itself and let the base class do the part they have in common.

Call base function then inherited function

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}

Categories

Resources