rspec/rules/S1006/csharp/rule.adoc

99 lines
1.9 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2020-06-30 12:47:33 +02:00
Default arguments are determined by the static type of the object. If a default argument is different for a parameter in an overriding method, the value used in the call will be different when calls are made via the base or derived object, which may be contrary to developer expectations.
2021-02-02 15:02:10 +01:00
2020-06-30 12:47:33 +02:00
Default parameter values are useless in explicit interface implementations, because the static type of the object will always be the implemented interface. Thus, specifying default values is useless and confusing.
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
using System;
public class Base
{
public virtual void Write(int i = 42)
{
Console.WriteLine(i);
}
}
public class Derived : Base
{
public override void Write(int i = 5) // Noncompliant
{
Console.WriteLine(i);
}
}
public class Program
{
public static void Main()
{
var derived = new Derived();
derived.Write(); // writes 5
Print(derived); // writes 42; was that expected?
}
private static void Print(Base item)
{
item.Write();
}
}
----
=== Compliant solution
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
using System;
public class Base
{
public virtual void Write(int i = 42)
{
Console.WriteLine(i);
}
}
public class Derived : Base
{
public override void Write(int i = 42)
{
Console.WriteLine(i);
}
}
public class Program
{
public static void Main()
{
var derived = new Derived();
derived.Write(); // writes 42
Print(derived); // writes 42
}
private static void Print(Base item)
{
item.Write();
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]