Red Gate forums :: View topic - Odd Constructor Initializer
Return to www.red-gate.com RSS Feed Available

Search  | Usergroups |  Profile |  Messages |  Log in  Register 
Go to product documentation
.NET Reflector 7.0 Feedback
.NET Reflector 7.0 Feedback forum

Odd Constructor Initializer

Search in .NET Reflector 7.0 Feedback forum
Post new topic   Reply to topic
Jump to:  
Author Message
billrob458



Joined: 29 May 2012
Posts: 2

PostPosted: Tue May 29, 2012 4:32 am    Post subject: Odd Constructor Initializer Reply with quote

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:
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:

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;
      }
   }
}
Back to top
View user's profile Send private message
nick.maidment



Joined: 29 Jan 2010
Posts: 74

PostPosted: Tue May 29, 2012 8:44 am    Post subject: Reply with quote

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/ Smile
Back to top
View user's profile Send private message
billrob458



Joined: 29 May 2012
Posts: 2

PostPosted: Tue May 29, 2012 1:54 pm    Post subject: Reply with quote

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.
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic All times are GMT + 1 Hour
Page 1 of 1

 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group