I have a base class and 2 inheriting classes, and I need to use the base class properties
in different way in each of the inheriting classes. what would be the elegant way of implementing it?
I have a class basic that have maintains two different averages.
and the inheriting classes have a same method getAction(), and each one of them does a different calculation and base on the calculation it returns an action.
I want to have one instance of the averages for both of the inheriting classes.
Avoid inheritance if you can. The solution below is an implementation of the strategy pattern which should suit your needs perfectly.
class Params
{
public int First {get;set;}
public int Second {get;set;}
}
interface IAverageCounter
{
double Calculate(Params parameters);
}
class SomeAverage : IAverageCounter
{
public double Calculate(Params parameters)
{
return (parameters.First + parameters.Second) / 2;
}
}
class OtherAverage : IAverageCounter
{
public double Calculate(Params parameters)
{
return (parameters.Second - parameters.First) / 2
}
}
I would override the methods you need:
MSDN
Use the override modifier to modify a method, a property, an indexer,
or an event. An override method provides a new implementation of a
member inherited from a base class. The method 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.
public class BaseClass
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double Area()
{
return x*x;
}
}
class InhertingClass1: BaseClass
{
// Constructor:
public Cube(double x): base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (6*(base.Area()));
}
}
class InhertingClass2: BaseClass
{
// Constructor:
public Cube(double x): base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (15*(base.Area()));
}
}
Related
I'm sure this question is somewhere else but can't find it.
I have an abstract class that will be the base for other classes.
want for the base class to have its base constructor inaccessible, and for the child classes not being able to edit the behavior, forcing them to use another constructor.
public abstract class BaseClass
{
protected int X;
private BaseClass() { } // Problematic accessor
public BaseClass(int x)
{
X = x;
}
}
public class Child : BaseClass
{
public Child(int x)
{
X = x + 5;
}
}
If I set the BaseClass() base constructor private it doesn't compile, but if I set it to protected, Child can override it.
There is a way to block Child modifying the base constructor?
EDIT: I want the base constructor to be inaccessible outside the class too.
If you don't want do anything in the
BaseClass()
constructor, just remove it (BaseClass has an explicit constructor and that's why doesn't have a default one):
public abstract class BaseClass
{
//TODO: probably you want a property to read X
private int X; // <- private looks better for fields
public BaseClass(int x)
{
X = x;
}
}
As for Child class you have to invoke its base constructor, i.e. base(int x):
public class Child : BaseClass
{
public Child(int x)
: base(x + 5) // since X is private, let's move logic into the call
{
}
}
You need to use the correct base class constructor to do what you want:
public class Child : BaseClass
{
public Child(int x) : base(x)
{
X = X + 5;
}
}
Note that the Child constructor body now uses the protected field X, not the parameter x.
Just omit the parameter-less constructor altogether. Now, every derived class is forced to call public BaseClass(int x).
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.
I'm trying to come up with a very neat way to alter an existing class. I'll try to explain what I came up with using this example;
abstract class AbstractX
{
public abstract string X();
protected internal abstract int Y();
}
// Execute all methods on another instance of AbstractX
// This is why the method(s) are 'protected *internal*'
class WrappedX : AbstractX
{
AbstractX _orig;
public WrappedX(AbstractX orig)
{
_orig = orig;
}
public override string X()
{
return _orig.X();
}
protected internal override int Y()
{
return _orig.Y();
}
}
// The AbstractX implementation I start with
class DefaultX : AbstractX
{
public override string X()
{
// do stuff
// call Y, note that this would never call Y in WrappedX
var y = Y();
return y.ToString();
}
protected internal override int Y()
{
return 1;
}
}
// The AbstractX implementation that should be able to alter *any* other AbstractX class
class AlteredX : WrappedX
{
public AlteredX(AbstractX orig)
:base(orig)
{
}
protected internal override int Y()
{
Console.WriteLine("Sweet, this can be added to any AbstractX instance!");
return base.Y();
}
}
Right, so the way I intend to use this is;
AbstractX x = new DefaultX();
x = new AlteredX(x);
Console.WriteLine(x.X()); // Should output 2 lines
Or to step away from the abstract example for a second and make it more concrete (should be self-explanatory);
FileWriterAbstract writer = new FileWriterDefault("path/to/file.ext");
writer = new FileWriterSplit(writer, "100MB");
writer = new FileWriterLogged(writer, "path/to/log.log");
writer.Write("Hello");
But (back to the abstract example) this isn't going to work. The moment AlteredX.X() is called (which isn't overridden) it goes to WrappedX.X(), which of course runs DefaultX.X() which uses it's own Y() method, and not the one I defined in AlteredX. It doesn't even know it exists.
I'm hoping it's obvious why I want this to work, but I'll explain further to make sure;
If I don't use WrappedX to created AlteredX, AlteredX will not be 'applyable' to any AbstractX instance,
thus making something like the FileWriter above impossible. Instead of;
FileWriterAbstract
FileWriterDefault : FileWriterAbstract
FileWriterWrap : FileWriterAbstract
FileWriterSplit : FileWriterWrap
FileWriterLogged : FileWriterWrap
It would become;
FileWriterAbstract
FileWriterDefault : FileWriterAbstract
FileWriterSplit : FileWriterDefault
// Implement Logged twice because we may want to use it with or without Split
FileWriterLogged : FileWriterDefault
FileWriterLoggedSplit : FileWriterSplit
And if I then created a new one, I'd have to implement it 4 times because I'd want it usable with;
Default
Split
Logged
Split+Logged
And so on...
So with that in mind, what's the best way to achieve this? The best I could come up with (untested) is;
class DefaultX : AbstractX
{
protected internal override Func<string> xf { get; set; }
protected internal override Func<int> yf { get; set; }
public DefaultX()
{
xf = XDefault;
yf = YDefault;
}
public override string X()
{
return xf();
}
protected override int Y()
{
return yf();
}
string XDefault()
{
var y = Y();
return y.ToString();
}
int YDefault()
{
return 1;
}
}
class AlteredX : WrappedX
{
Func<int> _yfOrig { get; set; }
public AlteredX()
{
// I'm assuming this class member doesn't get overwritten when I set
// base.yf in the line below.
_yfOrig = base.yf;
base.yf = YAltered;
}
private int YAltered()
{
Console.WriteLine("Sweet, this can be added to any AbstractX instance!");
return yfOrig();
}
}
Even if this does work, it seems really messy... does anyone have any suggestions?
One way to handle this would be to defer all of the internal operations to a separate, perhaps, internal utility class and provide a way for the wrapping classes to replace the implementation of the utility class. Note: this example requires any concrete, non-wrapping class to implement the utility class. A wrapper class may or may not choose to wrap the utility class. The key here is that the getter/setter for the utilities class in the base (abstract) class doesn't allow it to be overridden, thus every inheriting class uses the utility class as defined by it's constructor. If it chooses not to create it's own utilities, it defaults to that of the class it's wrapping - eventually making it all the way back to the concrete, non-wrapped composition root class if need be.
NOTE: this is very complex and I would avoid doing it. If possible use the standard decorator and only rely on public interface methods of the wrapped class. Also, the utility classes need not be inner classes. They could be injected via the constructor which might make it a bit cleaner. Then you would explicitly use the Decorator pattern on the utilities as well.
public interface IFoo
{
string X();
}
public abstract class AbstractFoo : IFoo
{
public abstract string X();
protected internal Footilities Utilities { get; set; }
protected internal abstract class Footilities
{
public abstract int Y();
}
}
public class DefaultFoo : AbstractFoo
{
public DefaultFoo()
{
Utilities = new DefaultFootilities();
}
public override string X()
{
var y = Utilities.Y();
return y.ToString();
}
protected internal class DefaultFootilities : Footilities
{
public override int Y()
{
return 1;
}
}
}
public abstract class AbstractWrappedFoo : AbstractFoo
{
protected readonly AbstractFoo Foo;
public AbstractWrappedFoo(AbstractFoo foo)
{
Foo = foo;
}
public override string X()
{
return Foo.X();
}
}
public class LoggedFoo : AbstractWrappedFoo
{
public LoggedFoo(AbstractFoo foo)
: base(foo)
{
Foo.Utilities = new LoggedUtilities(Foo.Utilities);
}
public override string X()
{
return Foo.X();
}
protected internal class LoggedUtilities : Footilities
{
private readonly Footilities _utilities;
public LoggedUtilities(Footilities utilities)
{
_utilities = utilities;
}
public override int Y()
{
Console.WriteLine("Sweet");
return _utilities.Y();
}
}
}
Now, this program
class Program
{
static void Main(string[] args)
{
AbstractFoo foo = new LoggedFoo(new DefaultFoo());
Console.WriteLine(foo.X());
}
}
Produces
Sweet!
1
I think you mixed up composition with inheritance.
When you call x.X() on an AlteredX object, the object calls X method of it's base object (WrappedX). The base object itself calls an object of type DefaultX which it has already wrapped. Now the Y method is called on an an object of DefaultX (_orig). You expect _orig knows there is something overriden in the caller of the caller! But how?
In this chain of call I don't see any point where overriding the method Y is involved.
Say you have access to a base class 'MyClass' that implements 'IFoo'. 'IFoo' defines the function 'int FooValue()' and 'MyClass' implements it explicitly. Now say you have a subclass of 'MyClass' called 'MySubClass' and you want to override 'FooValue' in that subclass, but you also want the subclass's implementation to be based on the result from the base class's implementation.
Now normally, this would be solved by simply moving the implementation to a protected function in the base class which we'd then simply overide in the subclass. Done and done. But we don't have access to the source code of the base class. We only have it as a reference to a library. So how do you solve this?
Not a Duplicate (update: ...as this one)!
There's this SO question here... C#: Property overriding by specifying the interface explicitly... that shows while you can't override a base class's interface through the normal channels per se, you can explicitly re-implement the same interface on a subclass and that behaves like you're overriding the interface (but in actuality you're re-implementing it, not overriding it.) That said, what I'm trying to figure out is how do I get at the base class's implementation. (That's why IMHO this isn't a duplicate of that question.)
Here's some pseudocode of the base class which again, we don't have access to code-wise...
public interface IFoo
{
int FooValue();
}
public class MyClass : IFoo
{
int IFoo.FooValue() <-- Explicit implementation requiring a cast to access.
{
return 4;
}
}
This is what we're trying to do, but obviously this isn't allowed because you can't use 'base' like this.
public class MySubClass : MyClass
{
int IFoo.FooValue()
{
int baseResult = ((IFoo)base).FooValue(); <-- Can't use 'base' like this
return baseResult * 2;
}
}
So is this possible?
I will be honest, there is no straightforward answer to this. Feels like a limitation of the language. May be there is some sound reason for the lack of it.
However, I can think of some not so clean work arounds.
Reflection. Imho, the simplest option here. One of those rare cases where reflection is really needed.
Your own interface and base class derived from referenced library.
//your interface
public interface IRealFoo : IFoo
{
new int FooValue();
}
//your base class
public class MyRealClass : MyClass, IRealFoo
{
protected virtual int FooValue()
{
return ((IFoo)this).FooValue();
}
int IRealFoo.FooValue()
{
return FooValue();
}
}
//your child class
public class MyRealSubClass : MyRealClass
{
protected override int FooValue()
{
return base.FooValue() * 2;
}
}
And you deal with IRealFoo, MyRealClass and so on instead of IFoo, MyClass etc.
IRealFoo x = new MyRealClass();
IRealFoo y = new MyRealSubClass();
Console.WriteLine(x.FooValue()); //4
Console.WriteLine(y.FooValue()); //8
Same as above but abstract class instead of interface.
Same as above, but you can also have an abstract base class RealFoo instead of interface IFoo. This I think is slightly easier code, but need not be good code. It completely changes the intent of the code.
public abstract class RealFoo : MyClass
{
public virtual int FooValue()
{
return ((IFoo)this).FooValue();
}
}
public class MyRealClass : RealFoo
{
public override int FooValue()
{
return base.FooValue();
}
}
public class MyRealSubClass : MyRealClass
{
public override int FooValue()
{
return base.FooValue() * 2;
}
}
//call it like:
RealFoo x = new MyRealClass();
RealFoo y = new MyRealSubClass();
Console.WriteLine(x.FooValue()); //4
Console.WriteLine(y.FooValue()); //8
Extension method along with dynamic.
public class MyRealClass : MyClass
{
public virtual int FooValue()
{
return ((IFoo)this).FooValue();
}
}
public class MyRealSubClass : MyRealClass
{
public override int FooValue()
{
return base.FooValue() * 2;
}
}
public static int RealFooValue(this IFoo foo)
{
return ((dynamic)foo).FooValue();
}
In this one case you can stick with familiar IFoo interface, but you got to call the extension method RealFooValue instead of FooValue. This will be confusing with potentially wrong result when calling FooValue. I dont advise it.
IFoo x = new MyRealClass();
IFoo y = new MyRealSubClass();
Console.WriteLine(x.RealFooValue()); //4
Console.WriteLine(y.RealFooValue()); //8
Switch on type with if-else logic.
public class MySubClass : MyClass
{
}
public static int RealFooValue(this IFoo foo)
{
var type = foo.GetType();
if (type == typeof(MyClass))
return foo.FooValue();
else if (type == typeof(MySubClass))
return foo.FooValue() * 2; //logic goes here
throw new Exception();
}
This has the same problem as above. Dont recommend it.
IFoo x = new MyClass();
IFoo y = new MySubClass();
Console.WriteLine(x.RealFooValue()); //4
Console.WriteLine(y.RealFooValue()); //8
Explicit interface realization means that IFoo.FooValue() is private
(you can check it by means of reflection):
MethodInfo mi = typeof(MyClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(m => m.Name.EndsWith("IFoo.FooValue")).ToList()[0];
if (mi.IsPrivate) {
// And it is private....
}
and so you can't call the
inherited IFoo.FooValue().
Possible byway
public interface IFoo
{
int FooValue();
}
public class MyClass : IFoo
{
// This (main logic) should be inherited/override
protected virtual int CoreFooValue()
{
return 4;
}
// Just a non-virtual interface method which is immutable
int IFoo.FooValue()
{
return CoreFooValue();
}
}
public class MySubClass : MyClass {
// Logic is changed, interface is not
protected override int CoreFooValue()
{
return base.CoreFooValue() * 2;
}
}
See also Non-virtual interface pattern
http://en.wikipedia.org/wiki/Non-virtual_interface_pattern
This question already has answers here:
What is the difference between an abstract method and a virtual method?
(28 answers)
Closed 4 years ago.
Here is some code from MSDN:
// compile with: /target:library
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
Can anyone explain the above code with respect to the differences between abstract and virtual methods?
Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.
So, abstract methods have no actual code in them, and (non-abstract) subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.
public abstract class E
{
public abstract void AbstractMethod(int i);
public virtual void VirtualMethod(int i)
{
// Default implementation which can be overridden by subclasses.
}
}
public class D : E
{
public override void AbstractMethod(int i)
{
// You HAVE to override this method
}
public override void VirtualMethod(int i)
{
// You are allowed to override this method.
}
}
First of all you should know the difference between a virtual and abstract method.
Abstract Method
Abstract Method resides in abstract class and it has no body.
Abstract Method must be overridden in non-abstract child class.
Virtual Method
Virtual Method can reside in abstract and non-abstract class.
It is not necessary to override virtual method in derived but it can be.
Virtual method must have body ....can be overridden by "override keyword".....
Abstract Method:
If an abstract method is defined in a class, then the class should
declare as an abstract class.
An abstract method should contain only method definition, should not
Contain the method body/implementation.
An abstract method must be over ride in the derived class.
Virtual Method:
Virtual methods can be over ride in the derived class but not
mandatory.
Virtual methods must have the method body/implementation along
with the definition.
Example:
public abstract class baseclass
{
public abstract decimal getarea(decimal Radius);
public virtual decimal interestpermonth(decimal amount)
{
return amount*12/100;
}
public virtual decimal totalamount(decimal Amount,decimal principleAmount)
{
return Amount + principleAmount;
}
}
public class derivedclass:baseclass
{
public override decimal getarea(decimal Radius)
{
return 2 * (22 / 7) * Radius;
}
public override decimal interestpermonth(decimal amount)
{
return amount * 14 / 100;
}
}
an abstract method must be call override in derived class other wise it will give compile-time error
and in virtual you may or may not override it's depend if it's good enough use it
Example:
abstract class twodshape
{
public abstract void area(); // no body in base class
}
class twodshape2 : twodshape
{
public virtual double area()
{
Console.WriteLine("AREA() may be or may not be override");
}
}