I have a base class which has a method for moving files to appropriate folders. There are many different files with many different naming schemes. The moving and folder creation is the same for every file, but determining the date is different because of the differing file names. I am trying to do this:
public class FileBase
{
protected FileInfo _source;
protected string GetMonth()
{
// 2/3 Files have the Month in this location
// So I want this to be used unless a derived class
// redefines this method.
return _source.Name.Substring(Source.Name.Length - 15, 2);
}
public void MoveFileToProcessedFolder()
{
MoveFileToFolder(Properties.Settings.Default.processedFolder + GetMonth);
}
private void MoveFileToFolder(string destination)
{
....
}
}
public class FooFile : FileBase
{
protected new string GetMonth()
{
return _source.Name.Substring(Source.Name.Length - 9, 2);
}
}
public class Program
{
FooFile x = new FooFile("c:\Some\File\Location_20110308.txt");
x.MoveFileToProcessedFolder();
}
The problem is that this code results in the base class version of 'GetMonth' being invoked inside the 'MoveFileToProcessedFolder' method. I thought that with the 'new' keyword, this would hide the original implementation and allow the derived implementation to take over. This is not what is happening. Obviously I'm not understanding the purpose of new in this case, can anyone out there help me understand this?
Thanks.
mark the methods as virtual then override them in your derived classes. New allows you to change the signature of the item so if base class has method named void DoWork() you can declare int DoWork() in your derived class by using new keyword. This solves the implicit calls but you can still explicitly call the base class method.
Use virtual (base) and override (derived)
What you really want is to make the base class's method virtual and then override it in the subclass.
public class BaseClass {
public virtual int Foo() {
return 1;
}
}
public class SubClass : BaseClass {
public override int Foo() {
return 42;
}
}
It will only hide when referenced directly by the type that is hiding the method. But since you are calling the implementation from the base class it is deferring to the method defined there.
In your case it sounds like you want virtual implementations rather then method hiding.
public class FileBase
{
protected FileInfo _source;
protected virtual string GetMonth()
{
// 2/3 Files have the Month in this location
// So I want this to be used unless a derived class
// redefines this method.
return _source.Name.Substring(Source.Name.Length - 15, 2);
}
public void MoveFileToProcessedFolder()
{
MoveFileToFolder(Properties.Settings.Default.processedFolder + GetMonth());
}
private void MoveFileToFolder(string destination)
{
....
}
}
public class FooFile : FileBase
{
protected override string GetMonth()
{
return _source.Name.Substring(Source.Name.Length - 9, 2);
}
}
public class Program
{
FooFile x = new FooFile("c:\Some\File\Location_20110308.txt");
x.MoveFileToProcessedFolder();
}
In this case you need to use Virtual in the base class and Override in the derived class. It works the way you are expecting using `new' if you do as below.
class Program
{
static void Main(string[] args)
{
FileBase fb = new FileBase();
Console.WriteLine(fb.GetMonth());
FooFile ff = new FooFile();
Console.WriteLine(ff.GetMonth());
Console.ReadLine();
}
}
public class FileBase
{
public string GetMonth()
{
return "FileBase::GetMonth()";
}
}
public class FooFile : FileBase
{
public new string GetMonth() // Hides the base method
{
return "FooFile::GetMonth()";
}
}
Related
// Cannot change source code
class Base
{
public virtual void Say()
{
Console.WriteLine("Called from Base.");
}
}
// Cannot change source code
class Derived : Base
{
public override void Say()
{
Console.WriteLine("Called from Derived.");
base.Say();
}
}
class SpecialDerived : Derived
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
}
class Program
{
static void Main(string[] args)
{
SpecialDerived sd = new SpecialDerived();
sd.Say();
}
}
The result is:
Called from Special Derived.
Called from Derived. /* this is not expected */
Called from Base.
How can I rewrite SpecialDerived class so that middle class "Derived"'s method is not called?
UPDATE:
The reason why I want to inherit from Derived instead of Base is Derived class contains a lot of other implementations. Since I can't do base.base.method() here, I guess the best way is to do the following?
// Cannot change source code
class Derived : Base
{
public override void Say()
{
CustomSay();
base.Say();
}
protected virtual void CustomSay()
{
Console.WriteLine("Called from Derived.");
}
}
class SpecialDerived : Derived
{
/*
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
*/
protected override void CustomSay()
{
Console.WriteLine("Called from Special Derived.");
}
}
Just want to add this here, since people still return to this question even after many time. Of course it's bad practice, but it's still possible (in principle) to do what author wants with:
class SpecialDerived : Derived
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
var ptr = typeof(Base).GetMethod("Say").MethodHandle.GetFunctionPointer();
var baseSay = (Action)Activator.CreateInstance(typeof(Action), this, ptr);
baseSay();
}
}
This is a bad programming practice, and not allowed in C#. It's a bad programming practice because
The details of the grandbase are implementation details of the base; you shouldn't be relying on them. The base class is providing an abstraction overtop of the grandbase; you should be using that abstraction, not building a bypass to avoid it.
To illustrate a specific example of the previous point: if allowed, this pattern would be yet another way of making code susceptible to brittle-base-class failures. Suppose C derives from B which derives from A. Code in C uses base.base to call a method of A. Then the author of B realizes that they have put too much gear in class B, and a better approach is to make intermediate class B2 that derives from A, and B derives from B2. After that change, code in C is calling a method in B2, not in A, because C's author made an assumption that the implementation details of B, namely, that its direct base class is A, would never change. Many design decisions in C# are to mitigate the likelihood of various kinds of brittle base failures; the decision to make base.base illegal entirely prevents this particular flavour of that failure pattern.
You derived from your base because you like what it does and want to reuse and extend it. If you don't like what it does and want to work around it rather than work with it, then why did you derive from it in the first place? Derive from the grandbase yourself if that's the functionality you want to use and extend.
The base might require certain invariants for security or semantic consistency purposes that are maintained by the details of how the base uses the methods of the grandbase. Allowing a derived class of the base to skip the code that maintains those invariants could put the base into an inconsistent, corrupted state.
You can't from C#. From IL, this is actually supported. You can do a non-virt call to any of your parent classes... but please don't. :)
The answer (which I know is not what you're looking for) is:
class SpecialDerived : Base
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
}
The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.
EDIT:
Your edit works, but I think I would use something like this:
class Derived : Base
{
protected bool _useBaseSay = false;
public override void Say()
{
if(this._useBaseSay)
base.Say();
else
Console.WriteLine("Called from Derived");
}
}
Of course, in a real implementation, you might do something more like this for extensibility and maintainability:
class Derived : Base
{
protected enum Mode
{
Standard,
BaseFunctionality,
Verbose
//etc
}
protected Mode Mode
{
get; set;
}
public override void Say()
{
if(this.Mode == Mode.BaseFunctionality)
base.Say();
else
Console.WriteLine("Called from Derived");
}
}
Then, derived classes can control their parents' state appropriately.
Why not simply cast the child class to a specific parent class and invoke the specific implementation then? This is a special case situation and a special case solution should be used. You will have to use the new keyword in the children methods though.
public class SuperBase
{
public string Speak() { return "Blah in SuperBase"; }
}
public class Base : SuperBase
{
public new string Speak() { return "Blah in Base"; }
}
public class Child : Base
{
public new string Speak() { return "Blah in Child"; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Child childObj = new Child();
Console.WriteLine(childObj.Speak());
// casting the child to parent first and then calling Speak()
Console.WriteLine((childObj as Base).Speak());
Console.WriteLine((childObj as SuperBase).Speak());
}
}
public class A
{
public int i = 0;
internal virtual void test()
{
Console.WriteLine("A test");
}
}
public class B : A
{
public new int i = 1;
public new void test()
{
Console.WriteLine("B test");
}
}
public class C : B
{
public new int i = 2;
public new void test()
{
Console.WriteLine("C test - ");
(this as A).test();
}
}
You can also make a simple function in first level derived class, to call grand base function
My 2c for this is to implement the functionality you require to be called in a toolkit class and call that from wherever you need:
// Util.cs
static class Util
{
static void DoSomething( FooBase foo ) {}
}
// FooBase.cs
class FooBase
{
virtual void Do() { Util.DoSomething( this ); }
}
// FooDerived.cs
class FooDerived : FooBase
{
override void Do() { ... }
}
// FooDerived2.cs
class FooDerived2 : FooDerived
{
override void Do() { Util.DoSomething( this ); }
}
This does require some thought as to access privilege, you may need to add some internal accessor methods to facilitate the functionality.
In cases where you do not have access to the derived class source, but need all the source of the derived class besides the current method, then I would recommended you should also do a derived class and call the implementation of the derived class.
Here is an example:
//No access to the source of the following classes
public class Base
{
public virtual void method1(){ Console.WriteLine("In Base");}
}
public class Derived : Base
{
public override void method1(){ Console.WriteLine("In Derived");}
public void method2(){ Console.WriteLine("Some important method in Derived");}
}
//Here should go your classes
//First do your own derived class
public class MyDerived : Base
{
}
//Then derive from the derived class
//and call the bass class implementation via your derived class
public class specialDerived : Derived
{
public override void method1()
{
MyDerived md = new MyDerived();
//This is actually the base.base class implementation
MyDerived.method1();
}
}
As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up.
We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Hello from Base");
}
}
public class Derived : Base
{
public override void Foo()
{
base.Foo();
Console.WriteLine("Text 1");
WriteText2Func();
Console.WriteLine("Text 3");
}
protected virtual void WriteText2Func()
{
Console.WriteLine("Text 2");
}
}
public class Special : Derived
{
public override void WriteText2Func()
{
//WriteText2Func will write nothing when
//method Foo is called from class Special.
//Also it can be modified to do something else.
}
}
There seems to be a lot of these questions surrounding inheriting a member method from a Grandparent Class, overriding it in a second Class, then calling its method again from a Grandchild Class. Why not just inherit the grandparent's members down to the grandchildren?
class A
{
private string mystring = "A";
public string Method1()
{
return mystring;
}
}
class B : A
{
// this inherits Method1() naturally
}
class C : B
{
// this inherits Method1() naturally
}
string newstring = "";
A a = new A();
B b = new B();
C c = new C();
newstring = a.Method1();// returns "A"
newstring = b.Method1();// returns "A"
newstring = c.Method1();// returns "A"
Seems simple....the grandchild inherits the grandparents method here. Think about it.....that's how "Object" and its members like ToString() are inherited down to all classes in C#. I'm thinking Microsoft has not done a good job of explaining basic inheritance. There is too much focus on polymorphism and implementation. When I dig through their documentation there are no examples of this very basic idea. :(
I had the same problem as the OP, where I only wanted to override a single method in the middle Class, leaving all other methods alone. My scenario was:
Class A - base class, DB access, uneditable.
Class B : A - "record type" specific functionality (editable, but only if backward compatible).
Class C : B - one particular field for one particular client.
I did very similar to the second part of the OP posting, except I put the base call into it's own method, which I called from from Say() method.
class Derived : Base
{
public override void Say()
{
Console.WriteLine("Called from Derived.");
BaseSay();
}
protected virtual void BaseSay()
{
base.Say();
}
}
class SpecialDerived : Derived
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.BaseSay();
}
}
You could repeat this ad infinitum, giving, for example SpecialDerived a BaseBaseSay() method if you needed an ExtraSpecialDerived override to the SpecialDerived.
The best part of this is that if the Derived changes its inheritance from Base to Base2, all other overrides follow suit without needing changes.
If you want to access to base class data you must use "this" keyword or you use this keyword as reference for class.
namespace thiskeyword
{
class Program
{
static void Main(string[] args)
{
I i = new I();
int res = i.m1();
Console.WriteLine(res);
Console.ReadLine();
}
}
public class E
{
new public int x = 3;
}
public class F:E
{
new public int x = 5;
}
public class G:F
{
new public int x = 50;
}
public class H:G
{
new public int x = 20;
}
public class I:H
{
new public int x = 30;
public int m1()
{
// (this as <classname >) will use for accessing data to base class
int z = (this as I).x + base.x + (this as G).x + (this as F).x + (this as E).x; // base.x refer to H
return z;
}
}
}
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.
I am trying to create a class based on an abstract class and overwrite a function contained in the base class with another one that has a return type of "T" which is a type passed by the class.
e.g:
public abstract class DayInfo
{
public virtual void GetInfo()
{
throw new NotImplementedException();
}
}
public class DayInfo<T> : DayInfo
{
private T info;
public DayInfo(T data)
{
info = data;
}
public T GetInfo() // << This
{
return info;
}
}
Examples:
1
DayInfo info = new DayInfo<String>("Blah");
String stuff = info.GetInfo();
2
DayInfo info = new DayInfo<int>(25);
int stuff = info.GetInfo();
Is there any way to achieve this?
Edit 1:
I forgot to precise that I didn't used a class-passed type in the base class because I wanted to be able to use it as a generic type without having to define any type.
e.g:
public SortedDictionary<int, DayInfo> Data = new SortedDictionary<int, DayInfo>();
Edit 2:
Also, the point of the virtual function in the base class is that it will make the child classes throw an exception if the GetInfo() function is accessed but isn't overridden.
this is the way to achieve your goal:
public abstract class DayInfoA<T>
{
public virtual T GetInfo()
{
.......
}
}
public class DayInfoB<T> : DayInfoA<T>
{
private T info;
public DayInfoB(T data)
{
info = data;
}
public override T GetInfo() // << This
{
.........
}
}
and use it like this:
DayInfoB<int> info = new DayInfoB<int>(25);
int stuff = info.GetInfo();
Why dont you declare GetInfo() as dynamic?
This way the casting should be automatic. The only downside is that you'd lost the compiler assertions and if the variable that stores GetInfo() value can't do the cast, it'll throw a runtime error.
For example:
public abstract class DayInfo {
public abstract dynamic GetInfo();
}
public class DayInfo<T> : DayInfo {
private readonly T _info;
public DayInfo(T info) {
_info = info;
}
public override dynamic GetInfo() {
return _info;
}
}
You also could declare something like GetInfo<T>(ref T result), this way you can omit the T type from the method call and let the compiler infer it at runtime, the only downside is that you should pass the variable to store the result as an argument instead to get it returned by the method.
This can be produced with NVI pattern:
public abstract class DayInfo
{
protected virtual void GetInfoCore() {
throw new NotImplementedException();
}
// or
// protected abstract void GetInfoCore();
public void GetInfo() {
GetInfoCore();
}
}
public class DayInfo<T> : DayInfo
{
private T info;
public DayInfo(T data) {
info = data;
}
public new T GetInfo() { // << This
return info;
}
protected override void GetInfoCore() {
GetInfo();
}
}
No, not like it looks like you're wanting it (assuming you don't want to or cant alter the base class declaration). In order for the function to resolve to a polymorphic call, you need to have the same signature and return type. Otherwise it wont resolve the function polymorphically, it'll just call the base class version of the function since that's what it sees you calling (and the variable you've assigned your instance to is of the base class type).
You CAN do this, but it's pretty ugly:
DayInfo info = new DayInfo<String>("Blah");
String stuff = ((DayInfo<string>)info).GetInfo();
No, because the functions won't match up with different function signatures.
What you can do is define it like so:
public abstract class DayInfo
{
public virtual object GetInfo()
{
throw new NotImplementedException();
}
}
and in the derived class like this:
public object GetInfo() // << This
{
return info;
}
Then they would both have the same signature and the polymorphism would match up.
However, on the other end a cast will be required:
DayInfo info = new DayInfo<int>(25);
int stuff = (int)info.GetInfo();
Edit: As an aside unless there's more to it I'd make that into an interface or if the GetInfo really does nothing make the GetInfo purely abstract.
public abstract object GetInfo();
You could create a covariant interface instead of, or in addition to, a base class:
void Main()
{
IDayInfo dayInfo = new DayInfo<string>("hi!");
object info = dayInfo.GetInfo(); //info == "hi!"
}
public interface IDayInfo
{
object GetInfo();
}
public interface IDayInfo<out T> : IDayInfo
{
new T GetInfo();
}
public class DayInfo<T> : IDayInfo<T>
{
private T info;
public DayInfo(T data)
{
info = data;
}
public T GetInfo()
{
return info;
}
object IDayInfo.GetInfo()
{
return this.GetInfo();
}
}
(see Variance in Generic Interfaces for info on what covariance/contravariance are)
Note that object info (in my second line in Main) is as precise as you can get without casting in this example. Once you store the DayInfo<string> object in an IDayInfo<object> variable/field, as I did (and as you'd like to do in your dictionary), the stronger typing of string is, in a sense, forgotten and cannot be restored without a cast.
Update: added IDayInfo interface.
I often use the class-factory pattern whereby a class has a private constructor and a static method to create the class. This allows for the situation where the class cannot be constructed for some reason, and a null is returned - very handy.
I would like to be able to extend this to a factory method which creates a particular class from a hierarchy of derived classes depending on conditions. However I can't see a way of then hiding the constructors of the derived classes to force the use of the factory method. If the factory method is in the base class it no longer has access to the private constructors of derived classes. Putting a factory method in every derived class doesn't work as the required type must then be known beforehand. Nested classes might be a way if a class had access to the private members of a nested class, but sadly it seems that the nested classes have access to the private members of the enclosing class, but not the other way round.
Does anyone know of a way of doing this?
There are several possibilities, two of which are:
Put all those classes in one project and make the constructors internal. Other projects won't be able to call those constructors but the code inside that project can.
Make the constructors of those classes protected (instead of private) and create a private derived class in the class containing the factory method. Create an instance of that private class and return it.
Example for the second option:
public static class AnimalFactory
{
public static Animal Create(int parameter)
{
switch(parameter)
{
case 0:
return new DogProxy();
case 1:
return new CatProxy();
default:
throw new ArgumentOutOfRangeException("parameter");
}
}
private class DogProxy : Dog { }
private class CatProxy : Cat { }
}
public abstract class Animal { }
public class Dog : Animal
{
protected Dog() { }
}
public class Cat : Animal
{
protected Cat() { }
}
Here's the sample code I was working on when Daniel posted his answer. It looks like it's doing what he suggested:
public static class BaseFactory
{
public static Base Create(bool condition)
{
if (condition)
{
return Derived1.Create(1, "TEST");
}
else
{
return Derived2.Create(1, DateTime.Now);
}
}
}
public class Base
{
protected Base(int value)
{
}
protected static Base Create(int value)
{
return new Base(value);
}
}
public sealed class Derived1: Base
{
private Derived1(int value, string text): base(value)
{
}
internal static Derived1 Create(int value, string text)
{
return new Derived1(value, text);
}
}
public sealed class Derived2: Base
{
private Derived2(int value, DateTime time): base(value)
{
}
internal static Derived2 Create(int value, DateTime time)
{
return new Derived2(value, time);
}
}
[EDIT] And for Daniel's second suggestion:
public static class BaseFactory
{
public static Base Create(bool condition)
{
if (condition)
{
return new Derived1Creator(1, "TEST");
}
else
{
return new Derived2Creator(1, DateTime.Now);
}
}
private sealed class Derived1Creator: Derived1
{
public Derived1Creator(int value, string text): base(value, text)
{
}
}
private sealed class Derived2Creator: Derived2
{
public Derived2Creator(int value, DateTime time): base(value, time)
{
}
}
}
public class Base
{
protected Base(int value)
{
}
protected static Base Create(int value)
{
return new Base(value);
}
}
public class Derived1: Base
{
protected Derived1(int value, string text): base(value)
{
}
protected static Derived1 Create(int value, string text)
{
return new Derived1(value, text);
}
}
public class Derived2: Base
{
protected Derived2(int value, DateTime time): base(value)
{
}
protected static Derived2 Create(int value, DateTime time)
{
return new Derived2(value, time);
}
}
Note that this second approach means that the classes can't be sealed, unfortunately.
Rather than using methods inside the class itself as a factory implement the Factory pattern by means of a static class ("the factory") that returns the correct instance based on the logic you write.
You can intercept the derived type creation in the base class contructor and check that the caller is your factory using StackFrames:
protected Class1() //base class ctor
{
StackFrame[] stackFrames = new StackTrace().GetFrames();
foreach (var frame in stackFrames)
{
//check caller and throw an exception if not satisfied
}
}
How do you declare a method in C# that should be overridden (or overridable) by a dereived class - possibly even outside your assembly - but that should be callable only from within the actual class?
(i.e. like a private virtual function in C++)
[edit]
private virtual is exactly what I intend: "Here's a way to modify my behavior, but you are still not allowed to call this function directly (because calling it requires arcane invocations that only my base class shall do)"
So to clarify it: what is the best expression for that in C#?
When you say it should only be callable "within the actual class" do you mean the base class or the derived class? Neither of these is feasible on its own. The closest is to use a protected method, which means it can be called from the declaring class, the derived class, and any further-derived class.
C# makes a stronger guarantee for "private" than C++ does. In C++, you can indeed override a private virtual method. But that means that code in a base class can execute code in a derived class. Breaking the promise that the private method is truly private and can only be called by methods in the same class.
Something that doesn't help here is that C++ doesn't require repeating the virtual keyword. Leading up to hard to reverse-engineer mysteries like this one:
#include "stdafx.h"
#include <iostream>
class Base {
private:
virtual void Method() = 0;
public:
void Test() {
Method();
}
};
class Derived : public Base {
private:
void Method() { std::cout << "Who the heck called me?"; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Base* p = new Derived;
p->Test();
}
I agree there's a possible role for private inheritance. The C# language designers said No! though.
A private member is not visible to child classes. I think protected virtual will perform the way you'd like?
UPDATE:
Here in greater detail is an explaination of what you can do with inheritance and overriding functions within C#. I tried to use a somewhat meaningful example, but consider it understood that its a poor class design and I wouldn't ever recommend implementing the classes described in this way. However, I hope perhaps this will give you an avenue to approach solving your original problem in a manner that might be acceptable. There is no way to prevent a concrete class from calling any of its members, but if your structure is like this in anyway, perhaps its not issue.
public abstract class Animal
{
public void DisplayAttributes()
{
Console.WriteLine(Header());
Console.WriteLine("Name: " + Name());
Console.WriteLine("Legs: " + Legs());
Console.WriteLine();
}
protected virtual int Legs()
{
return 4;
}
private string Header()
{
return "Displaying Animal Attributes";
}
protected abstract string Name();
}
public class Bird : Animal
{
protected override string Name()
{
return "Bird";
}
protected override int Legs()
{
return 2;
}
}
public class Zebra : Animal
{
protected override string Name()
{
return "Zebra";
}
}
public class Fish : Animal
{
protected override string Name()
{
return "Fish";
}
protected override int Legs()
{
return 0;
}
private string Header()
{
return "Displaying Fish Attributes";
}
protected virtual int Gils()
{
return 2;
}
public new void DisplayAttributes()
{
Console.WriteLine(Header());
Console.WriteLine("Name: " + Name());
Console.WriteLine("Gils: " + Gils());
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
Bird bird = new Bird();
bird.DisplayAttributes();
//Displaying Animal Attributes
//Name: Bird
//Legs: 2
Zebra zebra = new Zebra();
zebra.DisplayAttributes();
//Displaying Animal Attributes
//Name: Zebra
//Legs: 4
Fish fish = new Fish();
fish.DisplayAttributes();
//Displaying Fish Attributes
//Name: Fish
//Gils: 2
List<Animal> animalCollection = new List<Animal>();
animalCollection.Add(bird);
animalCollection.Add(zebra);
animalCollection.Add(fish);
foreach (Animal animal in animalCollection)
{
animal.DisplayAttributes();
//Displaying Animal Attributes
//Name: Bird
//Legs: 2
//Displaying Animal Attributes
//Name: Zebra
//Legs: 4
//Displaying Animal Attributes
//Name: Fish
//Legs: 0
//*Note the difference here
//Inheritted member cannot override the
//base class functionality of a non-virtual member
}
}
}
In this example, Bird, Zebra, and Fish could all call their Name and Legs methods, but within the context if this example, there wouldn't necessarily be utility in doing so. Additionally, as shown by Fish, the DisplayAttributes() can be modified for an instance of a concrete derived class; but when you're looking at an Animal, as in the foreach loop, you get the base classes DisplayAttributes behavior, regardless of the actual type of animal. I hope this may help povide the type of functionality you would like to replicate.
Here's an example of what vboctor has already mentioned:
public class Base
{
private Func<Base, int> func;
protected void SetFunc(Func<Base, int> func)
{
this.func = func;
}
private void CallFunc()
{
if (func != null)
{
var i = func(this);
}
}
}
public class Sub : Base
{
private void DoFuncyStuff()
{
this.SetFunc(b => 42);
}
}
Did you consider the use of a delegate to do that? You can allow the derived class to set the delegate via some protected property or passing it to your constructor. You can also default the delegate to your internal implementation which is a private method on your base class.
Why do you need it to be private? Protected should be sufficient, here. You're asking the subclass author to write code that they can't call. What does this accomplish? They could use that code anyway.
As I read your question, you could mean two things.
First ,if if you want a function in Class A that can be overriden in Child Class B but is not visible to any outside class:
public class ClassA
{
protected virtual ReturnType FunctionName(...) { ... }
}
public class ClassB
{
protected override ReturnType FunctionName(...) { ... }
}
Second, if you want to force an implementing class to define the function:
public abstract class ClassA
{
protected abstract ReturnType FunctionName(...);
}
public class ClassB
{
protected override ReturnType FunctionName(...) { ... }
}
Another concept you might look at if you are just digging into C# that is kinda related is partial classes. This is the idea of two source files being combined at compile time to create one class, both from the same assembly:
File 1:
public partial class ClassA
{
private ReturnType FunctionName(...);
}
File 2:
public partial class ClassA
{
//actual implimentation
private ReturnType FunctionName(...){ ... };
}
Partials are not widely used except when dealing with designed-generated files, like the Linq2Sql files, or EDM, or WinForms, etc.
Guess this will not work out as you intended, but let me sketch some pseudo-code for you:
public interface BaseClassFunction {
void PleaseCallMe();
}
public class BaseClass {
private BaseClassFunction fn;
public BaseClass(BaseClassFunction fn) {
this.fn = fn;
}
private CallMe() {
fn.PleaseCallMe();
}
public PublicCallMe() {
CallMe();
}
}
private class DerivedClassFunction : BaseClassFunction {
void PleaseCallMe() { ... do something important ... }
}
public class DerivedClassFunction {
public DerivedClassFunction() : BaseClass(new DerivedClassFunction()) {
}
}