Use "Optional, DefaultParameterValue" attribute, or not?
c#, c#-4.0, optional-parameters
Solution
The difference is that by using the attributes explicitly, the compiler doesn't enforce the same strictness on type requirements.
public class C {
// accepted
public void f([Optional, DefaultParameterValue(1)] object i) { }
// error CS1763: 'i' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null
//public void g(object i = 1) { }
// works, calls f(1)
public void h() { f(); }
}
Note that even with `DefaultParameterValue`, you don't throw out type-safety: if the types are incompatible, this will still be flagged.
public class C {
// error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
//public void f([Optional, DefaultParameterValue("abc")] int i) { }
}
Problem
Is there any difference between using `Optional` and `DefaultParameterValue` attributes and not using them? ``` public void Test1([Optional, DefaultParameterValue("param1")] string p1, [Optional, DefaultParameterValue("param2")] string p2) { } public void Test2(string p1= "param1", string p2= "param2") { } ``` both work: ``` Test1(p2: "aaa"); Test2(p2: "aaa"); ```