Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ParameterInfo.DefaultValue and ParameterInfo.RawDefaultValue

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?

like image 528
nawfal Avatar asked Apr 24 '13 07:04

nawfal


1 Answers

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:

  • How to: Load Assemblies into the Reflection-Only Context

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.

like image 153
Rick Sladkey Avatar answered Oct 31 '22 06:10

Rick Sladkey