The use of ref or out in combination with 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
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
class MyClass
{
public void DoStuff(ref int i)
{
Console.WriteLine(i);
}
public static void Main()
{
var i = 42;
new MyClass().DoStuff(ref i);
}
}