89 lines
1.8 KiB
Plaintext
89 lines
1.8 KiB
Plaintext
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.
|
|
|
|
|
|
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
|
|
|
|
----
|
|
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
|
|
|
|
----
|
|
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();
|
|
}
|
|
}
|
|
----
|
|
|
|
include::../see.adoc[]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|