E
E
Eugene2019-10-14 16:01:58
OOP
Eugene, 2019-10-14 16:01:58

How to prevent subclasses from overriding a superclass method in C#?

I want to create objects that modify the string passed to them. At the same time, it is necessary that none of them forget to check whether the string is empty and whether it was passed at all.
=> I create a base abstract class that has two methods:
* Modify, which encapsulates this check and calls MakeTransform if the check
passes * MakeTransform is a method that directly performs the transformation. It is implemented by descendants

public abstract class Modifier
{
        public string Modify(string str)
        {
            if (str == null || str.Length == 0)
                throw new ArgumentNullException("Ошибка модификатора. Строка пустая.");

            return MakeTransform(str);
        }

        protected abstract string MakeTransform(string str);
}

I create a child. It will perform modification, for example, on a regular expression. I implement MakeTransform as expected. Now, as planned, it is enough for him to call Modify received from the parent, and all checks and other routine will be performed for him in a transparent way, so that he does not know. The template method is obtained.
But then I or another user of the class looked out the window, got distracted, and also wrote an implementation for Modify, which overlapped the parent one:
public class RegexModifier : Modifier
{
        private string _pattern;

        public RegexModifier(string pattern)
        {
            _pattern = pattern;
        }

        protected override string MakeTransform(string source)
        {
            return Regex.Match(source, _pattern).Value;
        }

        public string Modify(string source)
        {
            return source;
        }
}

As a result, obviously nothing works, the line skips without the intended modification
class Program
{
        static void Main(string[] args)
        {
            var rmod = new RegexModifier(@"[ \p{L}]*");
            Console.WriteLine(rmod.Modify("Hello World321"));  // Вместо ожидаемого Hello Wolrd получаем исходную строку
        }
}

which would not have happened if I had a mechanism at compile time to prevent overriding the parent Modify method.
There is sealed for methods, but it does not fit here. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shai_hulud, 2019-10-14
@tw1ggyz

Well, firstly, this is a warning about the fact that one method "closes" another method with its name.
Go to project settings and set :
By default in each new project, it should be true. all C# warnings (even according to the documentation) are developer errors.
On the problem: there are no ways to disable name overlap. You can write Roslyn analytics to find such overlaps, you can check at runtime that the descendant does not have the same method.

G
Griboks, 2019-10-14
@Griboks

which would not have happened if I had a mechanism at compile time to prevent overriding the parent Modify method.

At me at overlapping of methods the warning pops up in studio. You do not have?
Why doesn't he fit? Is a crutch better? Well... reflection gives great opportunities, but sealed is better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question