org.sonar.plugins.csharp.S4019.html Maven / Gradle / Ivy
Why is this an issue?
When a method in a derived class has:
- the same name as a method in the base class
- but types of parameters that are ancestors (for example
string
in the base class and object
in the derived class)
the result is that the base method becomes hidden.
As shown in the following code snippet, when an instance of the derived class is used, invoking the method with an argument that matches the less
derived parameter type will invoke the derived class method instead of the base class method:
class BaseClass
{
internal void MyMethod(string str) => Console.WriteLine("BaseClass: Method(string)");
}
class DerivedClass : BaseClass
{
internal void MyMethod(object str) => Console.WriteLine("DerivedClass: Method(object)"); // Noncompliant
}
// ...
BaseClass baseObj = new BaseClass();
baseObj.MyMethod("Hello"); // Output: BaseClass: Method(string)
DerivedClass derivedObj = new DerivedClass();
derivedObj.MyMethod("Hello"); // Output: DerivedClass: Method(object) - DerivedClass method is hiding the BaseClass method
BaseClass derivedAsBase = new DerivedClass();
derivedAsBase.MyMethod("Hello"); // Output: BaseClass: Method(string)
class BaseClass
{
internal void MyMethod(string str) => Console.WriteLine("BaseClass: Method(string)");
}
class DerivedClass : BaseClass
{
internal void MyOtherMethod(object str) => Console.WriteLine("DerivedClass: Method(object)"); // Compliant
}
// ...
BaseClass baseObj = new BaseClass();
baseObj.MyMethod("Hello"); // Output: BaseClass: Method(string)
DerivedClass derivedObj = new DerivedClass();
derivedObj.MyMethod("Hello"); // Output: BaseClass: Method(string)
BaseClass derivedAsBase = new DerivedClass();
derivedAsBase.MyMethod("Hello"); // Output: BaseClass: Method(string)
Keep in mind that you cannot fix this issue by using the new keyword or by marking the method in the base
class as virtual
and overriding it in the DerivedClass
because the parameter types are different.
Exceptions
The rule is not raised when the two methods have the same parameter types.
Resources
Documentation