Link to home
Start Free TrialLog in
Avatar of midfde
midfdeFlag for United States of America

asked on

Does C# virtual 'must be overriden' method exist?

Is there a way to define a class that:
1. can be  instantiated
2. has method that =must= be overridden
I want to be able to write something like code in the attached snippet and be sure that all classes involved override WriteLog(...) method of PacratEventLogBase class. If derived class does not it must cause compile time error.
void testLaterPacratEventLog1() {
string myName = new StackFrame(true).GetMethod().Name;
foreach (PacratEventLogBase pelb in new PacratEventLogBase[]{
   new PacratEventLogFile(3),
   new PacratEventLogOutput(myName),
   new PacratEventLogSystem(myName, 15) 
                    }
        )  {
                pelb.WriteLog("str");
            }
    }

Open in new window

Avatar of p_davis
p_davis

you can make it an interface that another class implements, that way any method in the interface will have to be stubbed in.
or you can make it abstract
Avatar of midfde

ASKER

Thanks, p_davis.
I want that compile time error prevented user from occasional missing of a method implementation.
If I understand it correctly, you are suggesting that the guy who derives its class has not only remember to implement the method but also remeber to derive it from a certain interface.
So please exemplify your first comment (the second one is irrelevant since abstract class cannot be instatiated, the third one is too general and too basic).
your class that is being derived from can implement that interface and the method will automatically be stubbed in without the developer having to implement it directly -- just derive from the class.

the only "failsafe" with this is that the stubbed in code will include a thrown exception-- the developer can simply comment this out and continue on without putting any code in it. but if the developer removes the method they will get a compile time error.
Avatar of midfde

ASKER

Are we on the same page please? See the attached image.
-.bmp
Avatar of midfde

ASKER

Sorry, you may want to download it (simply click on it).
ASKER CERTIFIED SOLUTION
Avatar of p_davis
p_davis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of midfde

ASKER

Thank you, p_davis.
I thought I couldn't find because of... me, not because of C#.
It looks pretty natural for me to get gains from polymorphism as in my attached snippet where a statement writes into three different output channels. I am just seeking way to make it safer.