83 lines
2.4 KiB
Plaintext
83 lines
2.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The use of https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref[ref] or https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier[out] in combination with https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute[Optional] attribute is both confusing and contradictory. `[Optional]` indicates that the parameter doesn't have to be provided, while `out` and `ref` mean that the parameter will be used to return data to the caller (`ref` additionally indicates that the parameter may also be used to pass data into the method).
|
|
|
|
|
|
Thus, making it `[Optional]` to provide the parameter in which you will be passing back the method results doesn't make sense. In fact, the compiler will raise an error on such code. Unfortunately, it raises the error on method calls where the `[Optional]` parameter has been omitted, not the source of the problem, the method declaration.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
class MyClass
|
|
{
|
|
public void DoStuff([Optional] ref int i) // Noncompliant
|
|
{
|
|
Console.WriteLine(i);
|
|
}
|
|
|
|
public static void Main()
|
|
{
|
|
new MyClass().DoStuff(); // Compilation Error [CS7036]
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
class MyClass
|
|
{
|
|
public void DoStuff(ref int i)
|
|
{
|
|
Console.WriteLine(i);
|
|
}
|
|
|
|
public static void Main()
|
|
{
|
|
var i = 42;
|
|
new MyClass().DoStuff(ref i);
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref[ref keyword]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier[out parameter modifier]
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute[OptionalAttribute]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove the "Optional" attribute, it cannot be used with "[ref|out]".
|
|
|
|
|
|
=== Highlighting
|
|
|
|
"[Optional]" attribute
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 8 Dec 2015, 09:24:45 Tamas Vajk wrote:
|
|
\[~ann.campbell.2] I changed this rule to suggest removing the ``++[Optional]++`` and not the ``++ref++``/``++out++``.
|
|
|
|
=== on 8 Dec 2015, 15:09:51 Ann Campbell wrote:
|
|
okay [~tamas.vajk]
|
|
|
|
endif::env-github,rspecator-view[]
|