3

I have a constructor with optional parameters. I would like to have an expression to invoke that constructor without providing the optional arguments (I mean let the object be constructed with default values of the parameters).

I read here An expression tree may not contain a call or invocation that uses optional arguments that this is not possible.

I mean

var ctorInfo = getIt;
var f = Expression.Lambda<Func<T>>(Expression.New(ctorInfo)).Compile();

fails with System.TypeInitializationException.

Alright, I will pass the default values. But how do I get the default values of the parameters?

ctorInfo.GetParameters().Select(??

Motive: Learning purpose, no real world application.

Edit: Edited out expression-tree tag since its not in the context of building expressions, valid in general too.

Community
  • 1
  • 1
nawfal
  • 70,104
  • 56
  • 326
  • 368

1 Answers1

3

According to the documentation for ParameterInfo.RawDefaultValue:

ctorInfo.GetParameters().Select( p => p.RawDefaultValue );

Hope it helps

EDIT: Corrected property because:

This property [DefaultValue] is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead.

svick
  • 236,525
  • 50
  • 385
  • 514
Sarrus
  • 586
  • 7
  • 21
  • Yes it does! Do you know the difference between `DefaultValue` and `RawDefaultValue`? – nawfal Apr 24 '13 at 07:01
  • Not exactly. I just gave a look up on msdn. However I assume `RawDefaultValue` is right for this purpose. – Sarrus Apr 24 '13 at 07:07
  • Ok, I made it a separate question here http://stackoverflow.com/questions/16185826/difference-between-parameterinfo-defaultvalue-and-parameterinfo-rawdefaultvalue – nawfal Apr 24 '13 at 07:24