overriding methods in C# and avoid duplicate code [duplicate] - c#

This question already has answers here:
Force base method call
(14 answers)
Closed 4 years ago.
I would like to override a method, but i still want the parent method to be called when i override. When i try to use :base() to call parent method, it says unexpected token.
public class A
{
public virtual void DoStuff()
{
//some code
}
}
public class B : A
{
public override void DoStuff() : base()
{
//some other code
}
}
In java i would be :
super.DoStuff()

You have the wrong syntax, you can call the base method using the base keyword anywhere in the body of the method. The :base() syntax is only for constructors.
public class A
{
public virtual void DoStuff()
{
//some code
}
}
public class B : A
{
public override void DoStuff()
{
base.DoStuff();
}
}

Related

Call subclass `new` method from parent [duplicate]

This question already has answers here:
Why does calling a method in my derived class call the base class method?
(16 answers)
Closed 3 years ago.
I have a base and sub class such as:
class BaseClass
{
public void MethodA()
{
MethodB();
}
public void MethodB()
{
Debug.Log("BaseClass MethodB");
}
}
class SubClass : BaseClass
{
public new void MethodB() // <- without `new` keyword there's a warning on this line
{
Debug.Log("SubClass MethodB");
base.MethodB();
}
}
When the MethodA of the BaseClass instance is called it calls MethodB but only of the BaseClass, and not of the SubClass first. e.g.
var subclass = new SubClass();
subclass.MethodA(); // Does not log "SubClass MethodB" first. Only logs "BaseClass MethodB"
How do you make sure the parent methods call the subclass methods?
Note, without the new keyword on the MethodB line, Visual Studio gives a warning: 'SubClass.MethodB()' hides inherited member 'BaseClass.MethodB()'. Use the new keyword if hiding was intended.
To get Subclass.MethodB to be called from your base class you need to use the virtual and override keywords. For example:
class BaseClass
{
public void MethodA() // invoking this will correctly log "SubClass MethodB" followed by "BaseClass MethodB"
{
MethodB();
}
public virtual void MethodB()
{
Debug.Log("BaseClass MethodB");
}
}
class SubClass : BaseClass
{
public override void MethodB()
{
Debug.Log("SubClass MethodB");
base.MethodB();
}
}

Calling derived class method instead base class method c# [duplicate]

This question already has answers here:
How do I call a derived class method from the base class?
(2 answers)
Closed 4 years ago.
I have this array in program
ClassA[] array=new ClassA[20];
array[0]=new ClassB();
array[1]=new ClassA();
This is the class file
public class ClassA
{
public void method()
{
Console.WriteLine("1");
}
}
public class ClassB : ClassA
{
public void method()
{
Console.WriteLine("2");
}
}
It writes 1, in both cases, but i want in first case to write 2, (to call method of ClassB).
How to do that?
You have to use override keyword in C# when you want to override method in child class.
public class ClassA
{
public virtual void method()
{
Console.WriteLine("1");
}
}
public class ClassB : ClassA
{
public override void method()
{
Console.WriteLine("2");
}
}
Regards.

Is the keyword "virtual" optional or mandatory in a overridable method? [duplicate]

This question already has answers here:
Overriding vs method hiding [duplicate]
(3 answers)
Closed 5 years ago.
In C #, why we don't have a compilation error even if we forget the keyword "Virtual" in a method of a base class, redefined in a derived class.
I learnded that this keyword is mandatory to override a method
is not it ?
public class Mother
{
public void Speak()
{
Console.WriteLine("Mother !");
}
}
public class Son : Mother
{
public void Speak()
{
Console.WriteLine("Son!!");
}
}
Should be :
public class Mother
{
public virtual void Speak()
{
Console.WriteLine("Mother !");
}
}
public class Son : Mother
{
public override void Speak()
{
Console.WriteLine("Son!!");
}
}
Basically, Virtual and Override works on dynamic binding. The dynamic binding will be decided at run-time Compiler doesn't know that which virtual method will override in the derived class. That why it doesn't give you an error. This will be decided at run-time. Which derived class will be using at run-time.

Virtual call in constructor with additional method [duplicate]

This question already has answers here:
Virtual member call in a constructor
(18 answers)
Closed 6 years ago.
I have the issue where I need to call a virtual function in my abstract class' constructor.
internal abstract class Item
{
protected Item(...)
{
...
CreateBuyButton(...);
}
protected abstract void CreateBuyButton(...);
}
If I have my code like this resharper is notifying me about the problem however if I refactor the call into another method resharper doesn't seem to count this as a problem and I'm not sure if it is a problem or not.
internal abstract class Item
{
protected Item(...)
{
...
GetValue(...);
}
protected abstract void CreateBuyButton(...);
private void GetValue(...)
{
CreateBuyButton(...);
}
}
Is this valid ? Will the problem still persist ?
Yes, it could still be a problem
When the constructor for your base class runs, the constructor(s) for the derived classes haven't run yet. If the overridden method contains logic that depends on the derived class' state, it could encounter issues, because the state hasn't been initialized yet.
You can avoid the problem by removing the logic from the constructor and using lazy initialization instead, e.g.
abstract class Item
{
private Button _buyButton = null;
public Item()
{
//Do nothing
}
public Button BuyButton
{
get
{
if (_buyButton == null) CreateBuyButton(); //Lazy initialization
return _buyButton;
}
}
public abstract void CreateBuyButton();
}
If you need to pass some state, you'll have to store it:
abstract class Item
{
private string _productName;
private Button _buyButton = null;
public Item(string productName)
{
_productName = productName;
}
public Button BuyButton
{
get
{
if (_buyButton == null) CreateBuyButton(_productName); //Lazy initialization
return _buyButton;
}
}
public abstract void CreateBuyButton(string caption);
}

Should you call base.methodName or this.methodName [duplicate]

This question already has answers here:
Difference between this and base
(9 answers)
Closed 9 years ago.
If you are writing code in a class that inherits from a base class and you want to call a protected or public method on that base class, is it best (right or wrong or otherwise) to call base.MyProtectedMethod() or this.MyProtectedMethod() (in c#)? What would the difference be? Both seem to work.
For example:
public class MyBase()
{
....
protected void DoStuff()
{
// some stuff
}
}
public class MyChildClass() : MyBase
{
public MyNewMethod()
{
// do some work
this.DoStuff();
base.DoStuff();
}
}
Does this just to the same thing twice in MyNewMethod?
This does exactly the same thing in MyNewMethod.
I would only recommend using base. when it is actually required, ie: when you need to explicitly calling the base class version of a method from within an overridden method.
Do you want to explicitly call up the parent class? Then use base.
If you don't want to, use this.
This shows a great example on using base.
Just to illustrate Reed and Kevin's answers:
namespace ConsoleApplication1
{
class A
{
public virtual void Speak()
{
Hello();
}
virtual protected void Hello()
{
Console.WriteLine("Hello from A");
}
}
class B : A
{
public override void Speak()
{
base.Hello(); //Hello from A
this.Hello(); //Hello from B
}
override protected void Hello()
{
Console.WriteLine("Hello from B");
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
b.Speak();
}
}
}

Categories