When this code runs the output is "Child running" even though I am casting it to the Parent class? Im probably doing it wrong, if so, how can i achieve the desired result of having an output of "Parent running"? The Parent instance = new Child(); has to remain like that.
class Program
{
class Parent
{
public virtual void Run()
{
Console.WriteLine("Parent running.");
}
}
class Child : Parent
{
public override void Run()
{
Console.WriteLine("Child running.");
}
}
static void Main(string[] args)
{
Parent instance = new Child();
(instance as Parent).Run();
Console.ReadLine();
}
}
EDIT:
Noticed if I remove the virtual keyword from the Parent class and mark the Child's version of this method as new it "solves" the issue.
class Program
{
class Parent
{
public void Run()
{
Console.WriteLine("Parent running.");
}
}
class Child : Parent
{
public new void Run()
{
Console.WriteLine("Child running.");
}
}
static void Main(string[] args)
{
Parent instance = new Child();
(instance as Parent).Run();
Console.ReadLine();
}
}
You basically can't (short of using tricks with reflection). That's how inheritance in C# works.
What you could do instead of overriding Run is to shadow it:
public class Parent
{
public void Run() => Console.WriteLine("Parent");
}
public class Child : Parent
{
public new void Run() => Console.WriteLine("Child");
}
var child = new Child();
child.Run(); // prints "Child"
((Parent)child).Run(); // prints "Parent"
Shadowing is rarely a good idea as it can be confusing when an object changes its behaviour depending on the type of its variable. For more on shadowing, have a look at e. g. this question.
virtual method should not do anything,it's just a contract,what your goal is a bad ideal.
you should do it like this:
public class animal
{
public virtual void eat()
{
//don't do anything
}
}
public class dog:animal
{
public override void eat()
{
//eat Meat
}
}
public class sheep:animal
{
public override void eat()
{
//eat grass
}
}
Related
Here is the code I currently have, the question follows after:
class Program
{
static void Main(string[] args)
{
var obj1 = new A();
obj1.DoIt();
obj1.SetFlyBehavior(new BehaviorB());
obj1.DoIt();
string input = Console.ReadLine();
}
};
class BaseOfA
{
protected ObjectBehavior behavior;
public void DoIt()
{
behavior.DoIt();
}
public void SetBehavior(ObjectBehavior ob) {
behavior = ob;
}
};
class A : BaseOfA {
public A() {
behavior = new BehaviorA();
}
}
interface ObjectBehavior {
void DoIt();
}
class BehaviorA : ObjectBehavior {
void ObjectBehavior.DoIt() {
Console.WriteLine("Behavior: A");
}
}
class BehaviorB : ObjectBehavior {
void ObjectBehavior.DoIt() {
Console.WriteLine("Behavior: B");
}
}
Now my question is, in this case, how am I going to make it work so that I can assign both BehaviorA and BehaviorB to instance obj1 as long as they implement ObjectBehavior?
You are calling obj.SetFlyBehaviour this method is not defined anywhere. The method you define on BaseOfA is called SetBehaviour. Once that is fixed the code you gave compiles fine for me
I've found some code that is a bit long in a method:
class Parent { }
class Son : Parent { }
class Daughter : Parent { }
class MainClass
{
private void Iterate(IEnumerable<Parent> list)
{
foreach (Parent item in list) {
if (item is Son) {
...SOME CODE...
}
else if (item is Daughter) {
...MORE CODE...
}
}
}
}
Because of this big if-else block, the method is quite large, and smells as bad design (OOP-wise).
I've tried to come up with something a bit more polymorphic, taking advantage of method-overloading via different type-paramaters, such as:
class MainClass
{
private static void DoSomething (Son son)
{
Console.WriteLine ("Son");
}
private static void DoSomething (Daughter daughter)
{
Console.WriteLine ("Daughter");
}
private static void DoSomething (Parent parent)
{
Console.WriteLine ("Parent");
}
private void Iterate(IEnumerable<Parent> list)
{
foreach (var item in list) {
DoSomething (item);
}
}
}
But this doesn't work because it always prints "Parent", so I guess I would need to downcast manually, which defeats the point a bit, and would not look elegant.
One last point: if you are tempted to recommend me to put the implementation of DoSomething in the derived classes of Parent, that is not possible, because of dependency problems (the assembly where these 3 classes live cannot have dependencies on some things that the SOME CODE and MORE CODE is calling).
So what would be the best approach to refactor this? Thanks!
There are several ways to do this asides from the switch statement you've already identified (which definitely gets clunky with more than a couple of types involved).
First of all, if you aren't likely to add subtypes, but you are likely to add other things to do with the subtypes, you can use the Visitor Pattern to mimic double dispatch.
class Parent
{
public abstract void Accept(IChildVisitor visitor);
}
class Son : Parent
{
public override void Accept(IChildVisitor visitor)
{
visitor.Visit(this);
}
}
class Daughter : Parent
{
public override void Accept(IChildVisitor visitor)
{
visitor.Visit(this);
}
}
interface IChildVisitor
{
Visit(Son son);
Visit(Daughter daughter);
}
class SomeCodeChildVisitor : IChildVisitor
{
public Visit(Son son)
{
...SOME CODE...
}
public Visit(Daughter daughter)
{
...SOME CODE...
}
}
class MainClass
{
private void Iterate(IEnumerable<Parent> list)
{
foreach (Parent item in list) {
item.Accept(new SomeCodeChildVisitor());
}
}
}
You can also use a Dictionary<Type,Action>
class Parent { }
class Son : Parent { }
class Daughter : Parent { }
class MainClass
{
// If you don't actually need a reference to the child
private void IDictionary<Type, Action> map =
new Dictionary<Type, Action>()
{
{ typeof(Son), () => ...SOME CODE... }
{ typeof(Daughter), () => ...SOME CODE... }
};
// If you do need a reference to the child
private void IDictionary<Type, Action<Parent>> otherMap =
new Dictionary<Type, Action<Parent>>()
{
{ typeof(Son), x => (Son)x. ...SOME CODE... }
{ typeof(Daughter), y => (Daughter)x. ...SOME CODE... }
};
private void Iterate(IEnumerable<Parent> list)
{
foreach (Parent item in list) {
// either
map[item.GetType()]();
// or
otherMap[item.GetType()](item);
}
}
}
You can also use the dynamic keyword
class Parent { }
class Son : Parent { }
class Daughter : Parent { }
class MainClass
{
private void Iterate(IEnumerable<Parent> list)
{
foreach (Parent item in list) {
Visit((dynamic)item);
}
}
private void Visit(Son son)
{
...SOME CODE...
}
private void Visit(Daughter daughter)
{
...SOME CODE...
}
}
You can also just filter the types straight out of your collection with Linq (especially if you only care about some subtypes and not others, e.g. if you're iterating through a Controls collection and you only care about Buttons)
class Parent { }
class Son : Parent { }
class Daughter : Parent { }
class MainClass
{
private void Iterate(IEnumerable<Parent> list)
{
foreach (Daughter daughter in list.OfType<Daughter>()) {
...SOME CODE...
}
}
}
In C# I generally recommend the dictionary approach, but any will do in a pinch.
The best situation is to move DoSomething() method to the classes. If not possible, maybe you still can use conditionals to polymorphism, but with the decorator pattern. In this case you can
Define an abstract class with an abstract method DoSomething(). Let's call it FamilyDecorator. It's a good idea to create a constructor which receives a Parent in his parameter, so you can save it as a protected variable (that means: visible to all of the derived classes).
Declare one decorator for each class on your assembly: ParentDecorator, SonDecorator, DaughterDecorator. These three classes inherit from FamilyDecorator and must override the DoSomething() method.
The trick is to create a method in the abstract class that returns one or another Decorator, based on type. That's the way you can separate which logic use on each case:
abstract class FamilyDecorator
{
protected Domain.Parent _member;
public abstract void DoSomething();
internal FamilyDecorator(Domain.Parent member)
{
_member = member;
}
public static FamilyDecorator GetDecorator(Domain.Parent item)
{
if(item.GetType() == typeof(Domain.Parent))
{
return new ParentDecorator(item);
}
else if (item.GetType() == typeof(Domain.Son))
{
return new SonDecorator(item);
}
else if (item.GetType() == typeof(Domain.Daughter))
{
return new DaughterDecorator(item);
}
return null;
}
}
class ParentDecorator : FamilyDecorator
{
internal ParentDecorator(Domain.Parent parent)
: base(parent)
{
}
public override void DoSomething()
{
Console.WriteLine("A parent");
}
}
class SonDecorator : FamilyDecorator
{
internal SonDecorator(Domain.Parent son)
: base(son)
{
this._member = son;
}
public override void DoSomething()
{
Console.WriteLine("A son");
}
}
class DaughterDecorator : FamilyDecorator
{
internal DaughterDecorator(Domain.Parent daughter)
: base(daughter)
{
}
public override void DoSomething()
{
Console.WriteLine("A daughter");
}
}
Then, in your Main class:
foreach (Parent item in list)
{
var decorator = FamilyDecorator.GetDecorator(item);
decorator.DoSomething();
}
This solution keeps the code very clean and takes advantage of polymorphism.
Edit
I don't think I like this solution because you're basically moving the
type checking from the foreach loop to the GetDecorator() method.
Polymorphism should allow you to do this without type checking
manually.
There is another solution, based on the same idea: to use reflection for the object construction.
In this case:
Instead of an abstract class you define an Interface that declares the DoSomething() method.
Now each decorator inherits from their corresponding class (Parent - ParentDecorator, Son - SonDecorator, etc.)
You need to change the constructors in the Decorator classes. They need to be public if you want to use reflection.
Finally, the GetDecorator() method just search for the derived class in the assembly. If found, it returns the decorator.
namespace FamilyNamespace
{
interface IFamily
{
void DoSomething();
}
class ParentDecorator : Domain.Parent, IFamily
{
private Domain.Parent _member;
public ParentDecorator(Domain.Parent parent)
{
this._member = parent;
}
public void DoSomething()
{
Console.WriteLine("A parent");
}
}
class SonDecorator : Domain.Son, IFamily
{
private Domain.Parent _member;
public SonDecorator(Domain.Parent son)
{
this._member = son;
}
public void DoSomething()
{
Console.WriteLine("A son");
}
}
class DaughterDecorator : Domain.Daughter, IFamily
{
private Domain.Parent _member;
public DaughterDecorator(Domain.Parent daughter)
{
this._member = daughter;
}
public void DoSomething()
{
Console.WriteLine("A daughter");
}
}
}
Then in your Main class:
static FamilyNamespace.IFamily GetDecorator(Domain.Parent item)
{
var baseType = item.GetType();
var derivedType = Assembly.GetExecutingAssembly().GetTypes().Where(m => m != baseType && baseType.IsAssignableFrom(m));
if (derivedType.Any())
{
return (FamilyNamespace.IFamily)Activator.CreateInstance(derivedType.First(), new object[] { item });
}
return null;
}
... and the Main method:
foreach (Domain.Parent item in list)
{
var decorator = (FamilyNamespace.IFamily)GetDecorator(item);
decorator.DoSomething();
}
Greetings
The code below throws an exception because the abstract constructor is called before the child constructor.
I need to provide an abstract class to capsule some logic from a different part of the program. However i also need to check if the abstract members are initialised correctly rigth after creation without the childclass having any influence over this.
the compiling example below should illustrate my question.
using System;
namespace Stackoverflow
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
Thing childthing;
public Child(Thing provided) : base(){
childthing = provided;
}
public override void Initialise(){
//Exception is thrown here - childthing is still null
parentthing = childthing.Add(1);
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent(){
Initialise();
AssertThingyNotNull();
}
private void AssertThingyNotNull(){
if (parentthing == null) throw new Exception("Waaa");
}
public abstract void Initialise();
}
class Thing
{
private int i;
public Thing(int i){
this.i = i;
}
public Thing Add(int b){
i += b;
return new Thing(i);
}
}
}
Edit #1:
Is there some way to do this by reflecting into the caller (should be the creator of child rigth?) and then reacting on the end of that call?
Edit #2:
Getting the .ctor that creates the child is easy. Manipulating the methods seems something between impossible and a bad idea.
foreach (StackFrame frame in new StackTrace().GetFrames())
{
Console.WriteLine(frame.GetMethod().Name);
}
You can't, basically. This is why you should avoid calling virtual (or abstract) members from a constructor as far as possible - you could end up with code which is running with an incomplete context. Any variable initializers are executed before the base class constructor is called, but none of the code within the constructor body is.
If you need to perform initialization and only want to do that when the derived class constructor is running, then just call Initialise from the derived class constructor to start with.
You can do something similar to what Microsoft did with InitializeComponent()
then let the children call it whenever it can.
Try this.
Edited = cleaner version.
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
public Child(Thing provided)
: base()
{
parentthing = provided;
base.Initialise();
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent()
{
}
private void AssertThingyNotNull()
{
if (parentthing == null) throw new Exception("Waaa");
}
public void Initialise()
{
AssertThingyNotNull();
}
}
class Thing
{
private int i;
public Thing(int i)
{
this.i = i;
}
public Thing Add(int b)
{
i += b;
return new Thing(i);
}
}
}
Consider this code sample:
public abstract class Parent
{
public int val;
public Parent()
{
val = 0;
}
public virtual void foo()
{
inc();
}
public virtual void inc()
{
val = val + 10;
}
}
public class Child : Parent
{
public override void foo()
{
base.foo();
}
public override void inc()
{
val++;
}
}
static void Main(string[] args)
{
Parent p = new Child();
Console.WriteLine("p.val = " + p.val); //Output: p.val = 0
p.foo();
Console.WriteLine("P.val = " + p.val); //Output: p.val = 1
}
I am assuming the inc() of the Parent class did not get called because {this} pointer is actually pointing to a Child object so the Child's version of inc() will be called from the Parent object's function foo(). Is there a way to force the Parent's function foo() to always call parent's function inc() Like you could in C++ with :: operator?
No, the only way you can call a virtual method non-virtually is with base.Foo. Of course, you could write a non-virtual method in Parent, and make Parent.foo() call that, as well as the default implementation of Parent.inc().
You're over-thinking the problem.
If you want non-virtual dispatch then don't make the methods virtual in the first place.
If you want both virtual and non-virtual dispatch then make two methods, one virtual and one static
For example:
class Base
{
protected static void NonVirtualFoo(Base b)
{
// Whatever
}
public virtual void Foo()
{
Base.NonVirtualFoo(this);
}
}
class Derived : Base
{
protected new static void NonVirtualFoo(Derived d)
{
// Whatever
}
public override void Foo()
{
Derived.NonVirtualFoo(this);
Base.NonVirtualFoo(this);
}
}
Use the right tool for the job. If you want virtual dispatch then call a virtual method. If you want static dispatch then call a static method. Don't try to take a hammer to a virtual method and make it statically dispatched; that's working against the entire purpose of the tool.
The Child instance will call its own type implementation.
foo() calls base.foo() and base.foo() calls inc(), which in this case inc() is from the Child, since the instance is Child type, and will use this implementation.
Well, it is actually possible as said here:
This does the trick:
public abstract class Parent
{
public int val;
public Parent()
{
val = 0;
}
public virtual void foo()
{
MethodInfo method = typeof(Parent).GetMethod("inc");
DynamicMethod dm = new DynamicMethod("BaseInc", null, new Type[] { typeof(Parent) }, typeof(Parent));
ILGenerator gen = dm.GetILGenerator();
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, method);
gen.Emit(OpCodes.Ret);
var BaseInc = (Action<Parent>)dm.CreateDelegate(typeof(Action<Parent>));
BaseInc(this);
}
public virtual void inc()
{
val = val + 10;
}
}
But it's only a proof of concept: it's horrible and totally breaks the polymorphism.
I don't think you can have a valid reason to write this.
The naive solution, to move the lock to the Parent class, has a different behaviour: I will not be able to call new Child1().Method1() and new Child2().Method1() simultaneously.
Is there any way to refactor the code below?
abstract class Parent
{
protected abstract Method1();
}
class Child1 : Parent
{
static object staticLock = new object();
public void Method1()
{
lock(staticLock)
{
// Do something ...
}
}
}
class Child2 : Parent
{
static object staticLock = new object();
public void Method1()
{
lock(staticLock)
{
// Do something else ...
}
}
}
I'm asking this because it's not only 2 child classes, so the real problem is bigger.
Have a method implemented by each child class that provides lock policy and move Method1 to base class as in your other question.
class Parent
{
public void Method1()
{
using(acquireLock())
{
Method1Impl();
}
}
protected abstract IDisposable acquireLock();
protected abstract void Method1Impl();
}
class Child : Parent
{
protected override IDisposable acquireLock()
{
// return some class that does appropriate locking
// and in Dispose releases the lock.
// may even be no-op locking.
}
}
Maybe this works
abstract class Parent
{
protected abstract object StaticLock { get; }
public void Method()
{
lock(staticLock)
{
MethodImpl();
}
}
protected abstract MethodImpl();
}
class Child1 : Parent
{
private static object staticLock = new object();
protected override object StaticLock { get { return staticLock; } }
protected override MethodImpl()
{
// Do something ...
}
}
class Child2 : Parent
{
private static object staticLock = new object();
protected override object StaticLock { get { return staticLock; } }
protected override MethodImpl()
{
// Do something else ...
}
}