Expanded functions #4252
Replies: 4 comments 6 replies
-
Sounds like something solvable relatively easily with an analyzer. You could denote which virtual methods should require invocation by an override and where that base call should occur. |
Beta Was this translation helpful? Give feedback.
-
Possibly but I would rather focus on working on my projects than having to detour and use an analyser.. I'm sure your answer could apply to other aspects of C# features that have been implemented over the years anyway...but then still ended being added. |
Beta Was this translation helpful? Give feedback.
-
Fair point though that is kind've hard to prove, but can't rule out the fact that some times people don't realise they need it until they its given to them ! I assumed features for C# would also regardless of audience need's be considered for ways to write more robust code in general.
What do you mean by narrowing ? This was not suggested to replace the original behaviour it was an added optional feature to expand upon it. It doesn't remove the original override/virtual behaviour if you choose not to use the required keyword then nothing changes and will not break anything. |
Beta Was this translation helpful? Give feedback.
-
Aside from writing an analyzer, this is much better served using the Template Method Pattern: public void DoTheThing() //Note: NOT virtual
{
//pre-execution checks
LetsDoIt();
//post-execution checks
}
protected virtual void LetsDoIt()
{
//default logic
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello
I was wondering if it would ever be possible to implement keywords for virtual functions that contractually require you to call the base virtual method.
Something like this:
public required virtual void DoSomething() {}
Then for overrides there are two keywords to define the order of the override (pre and post):
This can be expanded further by having the base function determine the priority order:
With this you never have to remember having to call the base function.
The normal virtual/override behaviour still exists if you simply don't include the required keyword, so you lose nothing ultimately, it just gives you the ability to be more strict on the usage of the function.
The reason I suggest this is because I make virtual methods with certain logic that all derived classes use so I need to call the base anyway, but if you forget or some one else uses your library and is unaware that they need to call base function then it breaks very easily and isn't always obvious on why the logic not working - I think it would make the code more rigorous.
If we have abstract methods that force functions to be defined in derived classes I don't see why we can't have the feature of enforcement for calling base virtual functions.
Beta Was this translation helpful? Give feedback.
All reactions