Odd Constructor Initializer

Moderators: Luke Jefferson, Greg.Tillman, Clive Tong

Odd Constructor Initializer

Postby billrob458 » Tue May 29, 2012 4:32 am

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.

Code: Select all
protected ValidationAttribute(string errorMessage) : this(func)
{
    Func<string> func = null;
    if (func == null)
    {
        func = () => errorMessage;
    }
}


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.

Code: Select all
public abstract class Adam
{
   protected Adam(Func<bool> myFunc)
   {

   }

   protected Adam()
      : this(func)
   {
      Func<bool> func = null;

      if (func == null)
         func = () => true;
   }

   protected Adam(bool errorMessage)
      : this(func)
   {
      Func<bool> func = null;
      if (func == null)
      {
         func = () => errorMessage;
      }
   }
}
billrob458
 
Posts: 2
Joined: Tue May 29, 2012 4:21 am

Postby nick.maidment » Tue May 29, 2012 8:44 am

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
 
Posts: 74
Joined: Fri Jan 29, 2010 1:55 pm

Postby billrob458 » Tue May 29, 2012 1:54 pm

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
 
Posts: 2
Joined: Tue May 29, 2012 4:21 am


Return to .NET Reflector 7.0 Feedback

Who is online

Users browsing this forum: No registered users and 0 guests