Knowing child class overriding method of parent class without additional flag - c#

How do I know that a child class is overriding the method of its parent class? Currently I'm using boolean flag which is set false on the parent class, and when a child is overriding it, the child must set the flag. While it is working, I wonder if there is cleaner solution for this problem.
// The parent class
public Class_A
{
protected bool _hasCheckData = false;
public bool HasCheckData
{
get { return _hasCheckData; }
}
public abstract bool CheckData(File fileToCheck)
{
return true;
}
}
// Lot's of children from class A, this is one of them
public Class_B : Class_A
{
public override bool CheckData(File fileToCheck)
{
// the following line will be duplicated for all Class_A's children
// who implemented the checking of the file. How to avoid this?
_hasCheckData = true;
// checking the file
// and return the result
}
}
public Class_C
{
public void Test(File fileToCheck)
{
Class_B fileAbcChecker = new Class_B();
if (fileAbcChecker.HasCheckData)
fileAbcChecker.CheckData(fileToCheck);
}
}

You can implement a CheckData() that does nothing in Class_A (so it's not abstract anymore). Then, in the relevant Class_B's, override this implementation. In Class_C, remove the if statement. In this way, CheckData() always gets called. By default, it does nothing, unless the class wishes to do something with it.

Related

How do I get a variable from a dervied class to be used when executing a method from a base class?

I'm trying to use two different derived classes that inherit from a base class, with each of them having a boolean variable that differs from the other. The boolean has been assigned in both the base and the derived classes. However, when I access a method from the derived class that is only declared in the base class, the boolean results in the base class's result.
I already tried executing a method in each class that initializes its declared variables. No change has been made.
public partial class Form2 : Form
{
public class BaseC : Form
{
public bool reversePlace = false;
public void computeInput(BaseC cc)
{
if (reversePlace)
{
//Execute condition
if (cc.reversePlace)
{
//Execute execution from other derived class
}
}
}
}
public class DerivedC1 : BaseC
{
public bool reversePlace = true;
}
public class DerivedC2 : BaseC
{
public bool reversePlace = false;
}
DerivedC1 C1 = new DerivedC1();
DerivedC2 C2 = new DerivedC2();
public Form2()
{
C1.computeInput(C2); //Should execute first condition for being true while ignoring the inner condtion for being false
}
}
I should be getting an if statement from C1 halfway complete while skipping the if condition for C2. C1's boolean should be true while C2's should be false. However, both booleans are instead regarded as false.
Make it a virtual property. When it's virtual and overridden, even code defined in the base class will look at the most-overridden property of the current instance.
public class BaseC : Form
{
public virtual bool ReversePlace => false;
//etc....
}
public class DerivedC1 : BaseC
{
public override bool ReversePlace => true;
}
public class DerivedC2 : BaseC
{
public override bool ReversePlace => false;
}
I would take some time to look into inheritance, specifically things like virtual properties and methods, and how to override them.
Your base class should generally be using the keyword virtual and overriding when necessary for child methods and classes.
Here is a link to help you get the general idea: https://www.c-sharpcorner.com/UploadFile/3d39b4/virtual-method-in-C-Sharp/
If you just want to set the value, not hide the inherited member from the base class, you can do so in the constructors.
...
public class DerivedC1 : BaseC
{
public DerivedC1()
{
this.reversePlace = true;
}
}
public class DerivedC2 : BaseC
{
public DerivedC2()
{
this.reversePlace = false;
}
}
...

Calling an overwritten child method from parent class?

I am wondering what would theoretically be the output of this code?
Basically I am overwriting a method in the child class but I am calling that
method in the parent class. I am hoping the output of this would be "Child"
public class Animal {
protected virtual void Activate() {
Debug.Log("Parent");
}
void CallStuff() {
Activate();
}
}
public class Frog : Animal {
override void Activate() {
Debug.Log("Child");
}
}
If I were to have a frog instance frog and call ...
frog.CallStuff();
What would the output be?
Perhaps some examples will explain best:
Let's start with a base class:
public class Parent {
public virtual string WhatAmI() {
return "Parent";
}
public string Output() {
return this.WhatAmI();
}
}
Calling the Output method will, of course, give you "Parent"
new Parent().Output(); // "Parent"
Now let's override that virtual method
public class OverridingChild : Parent {
public override string WhatAmI() {
return "Child";
}
Now when you call Output(), it returns "Child"
new OverridingChild().Output(); // "Child"
And if you cast it to a Parent, you get the same result:
((Parent) new OverridingChild()).Output(); // "Child"
If you want the base class's value, you have to call base from within the inheriting class:
public class OverridingChild : Parent {
public override string WhatAmI() {
return "Child";
public string OutputBase() {
return base.WhatAmI();
}
}
new OverridingChild().OutputBase(); // "Parent"
Now for the confusing bit - here's how you can get either value, depending on what class the compiler thinks the object is:
public class NewMethodChild : Parent {
// note that "new" keyword
public new string WhatAmI() {
return "Child";
}
Calling the method directly when the compiler thinks it's the inheriting class gets you the expected result:
new NewMethodChild().WhatAmI(); // "Child"
But if you cast it to the base class, you get the Parent result:
((Parent) new NewMethodChild()).WhatAmI(); // "Parent"
And if you call the Output method, because it is defined at the Parent class it doesn't see the new WhatAmI method of the inheriting class, so it also outputs the base value:
new NewMethodChild().Output(); // "Parent"
Hope that clears things up.
the output would be "Child" It inherited the Call Stuff function but overrode the Activate function so you'd get Child

C# calling parent property while the child property is being called

I wanna see if there is anyway that when the child property method is being called, it will call the parent property as well.
Note that the child is generated by a code generator from edmx. So I can't change anything except adding a partial class for the child class. (It might be too trouble to change the generator.)
The situation I am having :
I have a class "MyClass" that is automatically generated from the database. I can't change anything on it except adding a partial class or change the code generator.
Now, I need to "do something" whenever the property Name is being called. I am thinking if I can put a parent there and make it call the parent to do "something" when the child property is "Name" is being called.
What I want :
public class ClassBase
{
public string Name
{
get
{
CallMethod();
return Name;
}
}
}
public class MyClass : ClassBase
{
public string Name { get; set; }
}
MyClass myClass = new MyClass();
myClass.Name; < -- this will call the parent as well.
Is there anyway to do it?
Thanks in advance
Not really related but since you're not strictly using automatic properties in ClassBase, you should create a private string variable for Name. Something like _name or whatever your internal coding standards dictate.
public class ClassBase
{
private string _name;
public virtual string Name
{
get
{
CallMethod();
return _name;
}
set
{
_name = value;
}
}
}
public class MyClass : ClassBase
{
//Pretty pointless really since you're not doing anything with MyClass.Name.
public new string Name
{
get
{
return base.Name;
}
set
{
base.Name = value;
}
}
MyClass myClass = new MyClass();
myClass.Name; <-- this will call the parent as well.
Based on "can't change base class" comment there is pretty much nothing you can do to make some code to be executed instead/before/after base class because your property/method will not be called when your new class used as base class (see sample in details part).
Potential solution : if you need to extend specially designed parital class's and it provides extension poinst like CallMethod is marked as partial - it is expected for implemnting portion of the class to implement it :
partial public class ClassBase
{
partial void CallMethod();
public string Name {get {CallMethod(); return "";}}
}
// in generated portion of "ClassBase"
partial public class ClassBase
{
partial void CallMethod() { /* do something here */ }
}
Answer to exact "how to call base class property" is to use base, but hiding property/method this way is confusing (see below):
new public string Name { get { return base.Name;} }
Note that you can't use automatic property in derived class case as you explicitly want some additional code to be executed. If you need set in derived class you need own backing field like:
private string derivedName;
new public string Name {
get { return base.Name + derivedName;}
set { derivedName = value;}
}
Details:
As said in comments hiding base class' properties/methods leads to very confusing behavior. For you case (slightly updated base class with baking field as original sample had infinite recursion):
public class ClassBase
{
private string name;
public string Name
{
get
{
CallMethod();
return name;
}
}
}
You can try to hide Name property in derived class:
public class MyClass : ClassBase
{
// notice "new" to show comiler you know what you doing
// otherwise you'll get warning (but behavior will be the same)
new public string Name { get; set; }
}
The issue with hiding is that base class' method is still easily callable and likely be called by mistake if using derived class as base class:
MyClass myDerved = new MyClass();
ClassBase myDervedAsBase = myDerved;
var name = myDerived.Name; // calls MyClass.Name
var name = myDerivedAsBase.Name; // calls ClassBase.Name
This can be solved by making base class' method/property virtual - but it requires change in base class:
public class ClassBase
{
virtual public string Name { get {... } }
}
public class MyClass : ClassBase
{
override public string Name { get { ... } }
}
If you need to call base class' method/property from derived class usebase.MethodName() like:
override public string Name { get
{
// do some new stuff here
var baseName = base.Name;
// maybe even change result
return baseName;
}
}
If you expect most derived classes to need such behavior it could be better to design base class explicitly to enforce such behavior. For example you can have property to call virtual method before/after computing the value to return like:
public class ClassBase
{
virtual protected string AboutToReturnName(string result)
{
return name;
}
public string Name
{
get
{
var result = "MyName";
return AboutToReturnName(result);
}
}
}
More ideas:
Alternative to virtual is partial methods which works when instead of deriving class is combined from many "partial" parts like ASP.Net pages - see Partial Classes and Methods
If you need notifications around change of property - consider implementing INotifyPropertyChange
if you need to know when properties/method are called in general - consider using interfaces and automatically generate wrapper classes that have pre/post callback. I.e. mocking frameworks (like EasyMoq or RhinoMock) and DI containers (like Unity) provide and use such functionality.
You cannot do it without modifying the code generator. The modification would have to generate a call base.Name.
You can override the property in your subclass with the new operator.
public class MyClass : ClassBase
{
public new string Name { get; set; }
}

Using a baseclass method return value?

I have a method in my baseclass that returns a bool and I want that bool to determine what happens to the same overridden method in my derived class.
Base:
public bool Debt(double bal)
{
double deb = 0;
bool worked;
if (deb > bal)
{
Console.WriteLine("Debit amount exceeds the account balance – withdraw cancelled");
worked = false;
}
else
bal = bal - deb;
worked = true;
return worked;
}
Derived
public override void Debt(double bal)
{
// if worked is true do something
}
Note that bal comes from a constructor I made earlier
You can call the base class method using the base keyword:
public override void Debt(double bal)
{
if(base.Debt(bal))
DoSomething();
}
As indicated in the comments above, you either need to make sure that there is a virtual method with the same signature (return type and parameters) in the base class or remove the override keyword from the deriving class.
if(base.Debt(bal)){
// do A
}else{
// do B
}
base refers to the base class. So base.X refers to X in the base class.
Call the base method:
public override void Debt(double bal)
{
var worked = base.Debt(bal);
//Do your stuff
}
As several others have mentioned you can use base.Debt(bal) to call into your base class method. I also noticed that your base class method was not declared as virtual. C# methods are NOT virtual by default so you will not be override it in a derived class unless you have specified it as virtual in the base class.
//Base Class
class Foo
{
public virtual bool DoSomething()
{
return true;
}
}
// Derived Class
class Bar : Foo
{
public override bool DoSomething()
{
if (base.DoSomething())
{
// base.DoSomething() returned true
}
else
{
// base.DoSomething() returned false
}
}
}
Here's what msdn has to say about virtual methods

Specification pattern implementation help

I've a question regarding enforcing a business rule via a specification pattern. Consider the following example:
public class Parent
{
private ICollection<Child> children;
public ReadOnlyCollection Children { get; }
public void AddChild(Child child)
{
child.Parent = this;
children.Add(child);
}
}
public class Child
{
internal Parent Parent
{
get;
set;
}
public DateTime ValidFrom;
public DateTime ValidTo;
public Child()
{
}
}
The business rule should enforce that there cannot be a child in the collection which validity period intersects with another.
For that I would like to implement a specification that is then be used to throw an exception if an invalid child is added AND as well can be used to check whether the rule will be violated BEFORE adding the child.
Like:
public class ChildValiditySpecification
{
bool IsSatisfiedBy(Child child)
{
return child.Parent.Children.Where(<validityIntersectsCondition here>).Count > 0;
}
}
But in this example the child accesses the parent. And to me that doesnt seem that correct. That parent might not exist when the child has not been added to the parent yet. How would you implement it?
public class Parent {
private List<Child> children;
public ICollection<Child> Children {
get { return children.AsReadOnly(); }
}
public void AddChild(Child child) {
if (!child.IsSatisfiedBy(this)) throw new Exception();
child.Parent = this;
children.Add(child);
}
}
public class Child {
internal Parent Parent { get; set; }
public DateTime ValidFrom;
public DateTime ValidTo;
public bool IsSatisfiedBy(Parent parent) { // can also be used before calling parent.AddChild
return parent.Children.All(c => !Overlaps(c));
}
bool Overlaps(Child c) {
return ValidFrom <= c.ValidTo && c.ValidFrom <= ValidTo;
}
}
UPDATE:
But of course, the real power of the specification pattern is when you can plug in and combine different rules. You can have an interface like this (possibly with a better name):
public interface ISpecification {
bool IsSatisfiedBy(Parent parent, Child candidate);
}
And then use it like this on Parent:
public class Parent {
List<Child> children = new List<Child>();
ISpecification childValiditySpec;
public Parent(ISpecification childValiditySpec) {
this.childValiditySpec = childValiditySpec;
}
public ICollection<Child> Children {
get { return children.AsReadOnly(); }
}
public bool IsSatisfiedBy(Child child) {
return childValiditySpec.IsSatisfiedBy(this, child);
}
public void AddChild(Child child) {
if (!IsSatisfiedBy(child)) throw new Exception();
child.Parent = this;
children.Add(child);
}
}
Child would be simple:
public class Child {
internal Parent Parent { get; set; }
public DateTime ValidFrom;
public DateTime ValidTo;
}
And you could implement multiple specifications, or composite specifications. This is the one from your example:
public class NonOverlappingChildSpec : ISpecification {
public bool IsSatisfiedBy(Parent parent, Child candidate) {
return parent.Children.All(child => !Overlaps(child, candidate));
}
bool Overlaps(Child c1, Child c2) {
return c1.ValidFrom <= c2.ValidTo && c2.ValidFrom <= c1.ValidTo;
}
}
Note that it makes more sense to make Child's public data immutable (only set through the constructor) so that no instance can have its data changed in a way that would invalidate a Parent.
Also, consider encapsulating the date range in a specialized abstraction.
I think the Parent should probably do the validation. So in the parent you might have a canBeParentOf(Child) method. This method would also be called at the top of your AddChild method--then the addChild method throws an exception if canBeParentOf fails, but canBeParentOf itself does not throw an exception.
Now, if you want to use "Validator" classes to implement canBeParentOf, that would be fantastic. You might have a method like validator.validateRelationship(Parent, Child). Then any parent could hold a collection of validators so that there could be multiple conditions preventing a parent/child relationship. canBeParentOf would just iterate over the validators calling each one for the child being added--as in validator.canBeParentOf(this, child);--any false would cause canBeParentOf to return a false.
If the conditions for validating are always the same for every possible parent/child, then they can either be coded directly into canBeParentOf, or the validators collection can be static.
An aside: The back-link from child to parent should probably be changed so that it can only be set once (a second call to the set throws an exception). This will A) Prevent your child from getting into an invalid state after it's been added and B) detect an attempt to add it to two different parents. In other words: Make your objects as close to immutable as possible. (Unless changing it to different parents is possible). Adding a child to multiple parents is obviously not possible (from your data model)
Would you not have an If statement to check that a parent was not null and if so return false?
You are trying to guard against Child being in an invalid state. Either
use the builder pattern to create fully populated Parent types so that everything you expose to the consumer is always in a valid state
remove the reference to the Parent completely
have Parent create all instances of Child so this can never occur
The latter case might look (something) like this (in Java):
public class DateRangeHolder {
private final NavigableSet<DateRange> ranges = new TreeSet<DateRange>();
public void add(Date from, Date to) {
DateRange range = new DateRange(this, from, to);
if (ranges.contains(range)) throw new IllegalArgumentException();
DateRange lower = ranges.lower(range);
validate(range, lower);
validate(range, ranges.higher(lower == null ? range : lower));
ranges.add(range);
}
private void validate(DateRange range, DateRange against) {
if (against != null && range.intersects(against)) {
throw new IllegalArgumentException();
}
}
public static class DateRange implements Comparable<DateRange> {
// implementation elided
}
}

Categories

Resources