This is a follow-up question of How do I get default values of optional parameters?
From documentation, DefaultValue:
Gets a value indicating the default value if the parameter has a default value.
This property is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead.
The default value is used when an actual value is not specified in the method call. A parameter can have a default value that is null. This is distinct from the case where a default value is not defined.
From documentation, RawDefaultValue:
Gets a value indicating the default value if the parameter has a default value.
This property can be used in both the execution context and the reflection-only context.
The default value is used when an actual value is not specified in the method call. A parameter can have a default value that is null. This is distinct from the case where a default value is not defined.
The documentation is so similar except that one is for reflection context and other not. What difference is that? When is ever DefaultValue
used without reflection at all? I mean how do we get a default value without reflection? Am I missing something?
Update
I created two overloads like this:
public void Required(string value)
{
}
public void Optional(string value = "", int i = -1)
{
}
I tested with:
var f = requiredInfo.GetParameters().Select(p => p.DefaultValue).ToArray();
var g = requiredInfo.GetParameters().Select(p => p.RawDefaultValue).ToArray();
var h = optionalInfo.GetParameters().Select(p => p.DefaultValue).ToArray();
var i = optionalInfo.GetParameters().Select(p => p.RawDefaultValue).ToArray();
//f equals g and h equals i in every way!
So what is the difference given that my test shows (all in reflection context) no difference at all?
There is a subtle but significant difference between "in the context of reflection" and "the reflection-only context". The "reflection only context" is referring to something very specific:
It is a way to load an assembly for examination only and has the distinct advantage of not requiring any dependent assemblies to be loaded or even to be present.
Since you appear to have every intention of executing some of the code you are reflecting, the reflection-only context would be of limited use to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With