Given a class like this:
public abstract class SomeClass
{
private string _name;
private int _someInt;
private int _anotherInt;
public SomeClass(string name, int someInt = 10, int anotherInt = 20)
{
_name = name;
_someInt = someInt;
_anotherInt = anotherInt;
}
}
Is it possible using reflection to get the optional parameter's default values?
DefaultValue
of theParameterInfo
class is what you are looking for:Lets take a basic program:
And look at some IL Code.
For Foo:
For Main:
Notice that main has 5 hardcoded as part of the call, and in Foo. The calling method is actually hardcoding the value that is optional! The value is at both the call-site and callee site.
You will be able to get at the optional value by using the form:
typeof(SomeClass).GetConstructor(new []{typeof(string),typeof(int),typeof(int)}) .GetParameters()[1].RawDefaultValue
On MSDN for DefaultValue (mentioned in the other answer):
This property is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead. MSDN
And finally a POC:
http://bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx