Inherit from a non-abstract class - c#

I have several classes which inherit from a BaseClass which has an abstract method called GetData. In one of them I want to basically inherit from again and provide use a new method called GetArticles which I call from GetData. Here's the code.
public abstract class BaseClass
{
internal abstract void GetData();
}
internal class FirstClass : BaseClass
{
internal override void GetData()
{
// calls GetArticles
}
protected void GetArticles()
{
}
}
internal class SecondClass : FirstClass
{
protected new void GetArticles()
{
}
}
GetArticles is never called in SecondClass. It calls the one in FirstClass, even though my object is of type SecondClass. I can't make GetArticles in FirstClass Abstract because I want to use FirstClass in its own right.
Any suggestions?

Your method has to marked as virtual in FirstClass and overriden using override keyword in SecondClass.
internal class FirstClass : BaseClass
{
internal override void GetData()
{
// calls GetArticles
}
protected virtual void GetArticles()
{
}
}
internal class SecondClass : FirstClass
{
protected override void GetArticles()
{
}
}
new modifier hides the underlying virtual method, which is not what you want. Check Knowing When to Use Override and New Keywords (C# Programming Guide) on MSDN.

Declare GetArticles in your FirstClass as virtual. In the second class remove new and add override

Make GetArticles virtual.
protected virtual void GetArticles()
{
}

Normal Class can not contain abstract method.Whereas abstract class can contain normal method.
If a normal class inherit abstract class and hold any abstract method than must be override due to inheritance in derived class.

Related

access protected members of another instance in derived class

Even though Iam in a derived class which should get me access to the derived protected members, I get the error
"Cannot access protected method 'BaseMethod' from here"
when trying to call other.BaseMethod();.
Can I get around this without having to make BaseMethod public? I also cannot make the method internal, since Base and Derived are in different assemblies.
class Base
{
protected void BaseMethod() { }
}
class Derived: Base
{
public void Doit(Base other)
{
other.BaseMethod();
}
}
You are using another class, as parameter, not the derived one.
in this case, the method should be public.
but have a look a this
How do you unit test private methods?
You can get around this by adding protected internal:
class Base
{
protected internal void BaseMethod() { }
}
class Derived : Base
{
public void Doit(Base other)
{
other.BaseMethod();
}
}
However, when inheritance is used then it can be called without any params. Let me show an example:
class Base
{
protected internal void BaseMethod() { }
}
class Derived : Base
{
public void Doit()
{
BaseMethod();
}
}

Insert code from child class method in middle of base class method [duplicate]

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()
{
}
}

Force base class virtual method call inside of base class

Don't get me wrong: I do not want to force an overriding method to call the base class like already asked 1000...times before :)
I wondered if there is any way to force the call of the base class implementation of a method inside the base class.
Example:
using System;
public class Program
{
public static void Main()
{
var c = new SubClass();
c.CallInfo();
}
internal class BaseClass {
protected virtual void Info(){
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo() {
this.Info();
}
}
internal class SubClass : BaseClass {
protected override void Info() {
Console.WriteLine("SubClass");
}
internal override void CallInfo() {
base.CallInfo();
}
}
}
Output obviously would be SubClass. Is there any way to force the CallInfo method of BaseClass to call its own Info method so that the output would be BaseClass?
By marking your Info() method as virtual you are specifically asking for this type of inheritance behaviour to occur.
If you want to ensure that a method call in your base class is not overridden, you'll need to use a non-virtual method, e.g.
internal class BaseClass {
protected virtual void Info(){
this.FinalInfo();
}
protected void FinalInfo() {
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo() {
this.FinalInfo();
}
}
No, you can't do that. The purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called it from base classes.
If that causes problems then the method you want to run should not be a virtual method.
This would work, while it won't force an implementation by a subclass like virtual it'll allow you to override it.
public class Program
{
public static void Main()
{
var c = new SubClass();
c.CallInfo();
}
internal class BaseClass
{
protected void Info()
{
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo()
{
this.Info();
}
}
internal class SubClass : BaseClass
{
protected new void Info()
{
Console.WriteLine("SubClass");
}
internal override void CallInfo()
{
base.CallInfo();
}
}
}

Inherit classes in c#

I have an abstract class and two classes derivated of this principal class:
abstract class MainClass
{
public void DoSomething() {
if(isEdit())
Edit();
else if(isNew())
New();
else if(isDelete())
Delete();
else if(isSearch())
Search();
else if(isExit())
Exit();
}
public abstract void Edit();
public abstract void New();
public abstract void Delete();
public abstract void Search();
public abstract void Exit();
}
abstract class FirstClass : MainClass
{
public abstract void Edit();
public abstract void New();
public abstract void Delete();
}
abstract class SecondClass : MainClass
{
public abstract void Search();
public abstract void Exit();
}
When you need to extend from FirstClass Edit(), New() and Delete() must be declared, and methods Search() and Exit() can be declared but should not be mandatory. Is there any way to do that?
When you need to extend from FirstClass Edit(), New() and Delete() must be declared, and methods Search() and Exit() can be declared but should not be mandatory.
That is possible:
abstract class FirstClass : MainClass
{
//public abstract void Edit();
//public abstract void New();
//public abstract void Delete();
public override void Search() { }
public override void Exit() { }
}
Edit(), New() and Delete() are already declared as abstract (must override) in the MainClass so FirstClass should leave them alone.
Implement the optional methods as overrides:
abstract class FirstClass : MainClass
{
public override void Search(){}
public override void Exit(){}
}
Since they are implemented in MainClass, you don't need to implement in any inheriting class, but if you want to, you can override them.
Note that you do not need to redeclare Edit, New and Delete again - they are already inherited by FirstClass and will need to be implemented by any non-abstract inheritor of it.
The abstract keyword indicates that a method MUST be implemented by an inheriting class. The virtual keyword indicates that it MAY be implemented.
Mark Save() and Exit() as virtual and provide a default (possibly empty) implementation of them.
You can override the non-mandatory methods that have been declared in MainClass which is the baseclass for FirstClass, and provide default functionality for it:
abstract class FirstClass : MainClass
{
public override void Search(){}
public override void Exit() {}
}
The mandatory methods should not be declared in FirstClass, since they're already declared as abstract in the MainClass. They remain abstract in FirstClass
Override methods which could be optionally declared in child classes (other methods will be inherited from MainClass and stay abstract):
abstract class FirstClass : MainClass
{
public override void Search() { /* default implementation */ }
public override void Exit() { /* default implementation */ }
}
Then
class ThirdClass : FirstClass
{
// Must implement abstract methods
public override void Edit() { }
public override void New() { }
public override void Delete() { }
// Optionally override
public override void Exit() { /* custom implementation */ }
}

abstract method in a virtual class

I have a c# Class that has lots of virtual methods, some of these methods are essentially abstract ( they are fully implemented in subclasses and the base class is empty).
To get it to compile i am throwing an InvalidOperationException in the base class with a comment on what should be done. This just feels dirty.
Is there a better way to design my classes?
edit:
It is for the middle tier of an application that will be ran in canada, half of the methods are generic hence the virtual. and half of the methods are province specific.
Public class PersonComponent()
{
public GetPersonById(Guid id) {
//Code to get person - same for all provinces
}
Public virtual DeletePerson(Guid id) {
//Common code
}
Public virtual UpdatePerson(Person p) {
throw new InvalidOperation("I wanna be abstract");
}
Public Class ABPersonComponent : PersonComponent
{
public override DeletePerson(Guid id)
{
//alberta specific delete code
}
public override UpdatePerson(Person p)
{
//alberta specific update codecode
}
}
hope this makes sense
Mark the base class as abstract, as well as the methods that have no implementation.
Like so
public abstract class BaseClass
{
public abstract void AbstractMethod();
}
public class SubClass: BaseClass
{
public override void AbstractMethod()
{
//Do Something
}
}
You can't have abstract methods outside of an abstract class. Marking a class as abstract means you won't be able to instantiate it. But then it doesn't make any sense to. What are you going to do with a class that doesn't implement the methods anyway?
Edit: From looking at your class, yeah I'd make PersonComponent abstract along with the UpdatePerson method. Either that, or if UpdatePerson just doesn't do anything for a PersonComponent keep it as is, but make the UpdatePerson method empty for PersonComponent.
Think about your object hierarchy. Do you want to share common code for all your derived classes, then implement base functionality in the base class.
When having shared base code, please notice the Template pattern. Use a public method and chain it to a protected virtual method with the core/shared implementation. End the shared implementation methodname with "Core".
For example:
public abstract class BaseClass
{
protected virtual void DeletePersonCore(Guid id)
{
//shared code
}
public void DeletePerson(Guid id)
{
//chain it to the core
DeletePersonCore(id);
}
}
public class DerivedClass : BaseClass
{
protected override void DeletePersonCore(Guid id)
{
//do some polymorphistic stuff
base.DeletePersonCore(id);
}
}
public class UsageClass
{
public void Delete()
{
DerivedClass dc = new DerivedClass();
dc.DeletePerson(Guid.NewGuid());
}
}

Categories