This might just be a fluke of the C# disassembler. I'm looking at the ValidationAttribute class of the System.ComponentModel.DataAnnotations (v4).

The ctors look off. I'm pretty sure this is how the code is behaving as the late bound Func<string> around the message is clearly working.

How is "func" passed to the ctor initializer *before* it is declared.
protected ValidationAttribute&#40;string errorMessage&#41; : this&#40;func&#41;
&#123;
    Func&lt;string&gt; func = null;
    if &#40;func == null&#41;
    &#123;
        func = &#40;&#41; =&gt; errorMessage;
    &#125;
&#125;

It would be amazing if we could apply complex default logic to pass to ctor initializer.

I tried doing this and it doesn't compile.
public abstract class Adam
&#123;
	protected Adam&#40;Func&lt;bool&gt; myFunc&#41;
	&#123;

	&#125;

	protected Adam&#40;&#41;
		: this&#40;func&#41;
	&#123;
		Func&lt;bool&gt; func = null;

		if &#40;func == null&#41;
			func = &#40;&#41; =&gt; true;
	&#125;

	protected Adam&#40;bool errorMessage&#41;
		: this&#40;func&#41;
	&#123;
		Func&lt;bool&gt; func = null;
		if &#40;func == null&#41;
		&#123;
			func = &#40;&#41; =&gt; errorMessage;
		&#125;
	&#125;
&#125;
billrob458
0

Comments

2 comments

  • nick.maidment
    The code Reflector is generating is incorrect. It is trying to do the equivalent of the following, which does compile.

    public Program(Func<string>x)
    {
    }

    public Program(string errorMessage)
    : this(() => errorMessage)
    {
    }

    Ie the stuff to do with the local variable func, is supposed to be happening inside the call to this(…)

    By the way, we also have a newer forum here: http://forums.reflector.net/ :)
    nick.maidment
    0
  • billrob458
    Thanks for the reply Nick. I figured as much that all the logic was inlined. I was hoping there was some special trick we could use to have more complex "default" parameters we could pass to a constructor initializer.
    billrob458
    0

Add comment

Please sign in to leave a comment.