OK.. C# is not my forte and it’s been a while since I got my head into this sort of thing and I have forgotten some things: I am struggling to get this too obey me 🙂 I am pretty sure what I want to do is possible within C# and I am pretty sure my abstracts and my interfaces are all to hell (I don’t even know how to put the interface in but I know I need one)
ok here is the scenario
//abstract parent class
abstract class ActionType
{
/***
* this is a parent class not meant to ever be instaciated
*/
public abstract void action();
}
class ActionTypeSync : ActionType
{
public override void action()
{
Debug.WriteLine("doing sync");
}
}
class ActionTypeRead : ActionType
{
public override void action()
{
Debug.WriteLine("doing read");
}
}
the following does not work
ActionType action = getActionType(1);
ActionType secondaction = getActionType(2);
[ EDIT ]
actually I was being too brief it’s THIS bit that didn’t work with error
Error Argument 1: cannot convert from ‘ActionType’ to ‘ActionTypeSync’
processThings(action);
//debug out put "doing sync"
processThings(secondaction);
//debug out put "doing sync"
public ActionType getActionType(int i)
{
if (i==1) return new ActionTypeSync();
if (i==2) return new ActionTypeRead();
}
public void processThings(ActionTypeSync action)
{
action.action();
}
public void processThings(ActionTypeRead action)
{
action.action();
}
[/ EDIT ]
How best do I need to restructure this.. please understand this is a an example for sake of brevity (as best as I could) I am summarising here – so some principles are better than some “why etc etc lectures” 🙂 thank you 🙂 I don’t object to restructure in order to accommodate the polymorphic principle but I need this basic polymoprphic interface/class structure as is
Overlooking your syntactical errors, this is doing exactly what you told it to do.It is calling the local
action()on the specific type you instantiated, it doesn’t do anything else because you haven’t told it to (i.e. at no stage are you callingbase.action()).Edit:
Based on your edit….
ActionTypeSyncandActionTypeReadcan both be cast down toActionType, butActionTypecannot be cast back up to either of those derived types. You can pass one of the derived objects around as anActionTypeand the overriddenaction()method will be called, but you can’t cast it implicitly or explicitly to the derived type. To fix this just change your method signatures:Because of this change you will now only need one method that will deal with both derived types because you have cast it down to its base type – IOW you can get rid of the
processThings(ActionTypeRead action)method.