Search code examples
visual-studio-2008visual-studio-2005c#-3.0oauthc#-2.0

() => construct


I am in the process of converting a project from visual studio 2005 to visual studio 2008 and came up on the above construct.

using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using CommonServiceLocator.WindsorAdapter;
using Microsoft.Practices.ServiceLocation;

namespace MyClass.Business
{
    public class Global : System.Web.HttpApplication
    {
        public override void Init()
        {
            IServiceLocator injector =
                new WindsorServiceLocator(
                    new WindsorContainer(
                        new XmlInterpreter(
                            new ConfigResource("oauth.net.components"))));

            //ServiceLocator.SetLocatorProvider(() => injector);

            // ServiceLocator.SetLocatorProvider(injector);
        }
    }
}

ServiceLocator.SetLocatorProvider(() => injector);

Can I get an understanding of what this is.


Solution

  • This is a lambda expression.

    I guess that the SetLocatorProvider method has a signature like:

    SetLocatorProvider( Func<IServiceLocator> callback ):
    

    Now you have to provide such a callback. There are basically three options:

    Use a method (always working):

    private IServiceLocator GetServiceLocator() { /* return IServiceLocator */ }
    
    ServiceLocator.SetLocatorProvider( GetServiceLocator() );
    

    Use a delegate (requires C#2.0):

    ServiceLocator.SetLocatorProvider( delegate
            {
                // return IServiceLocator
            } );
    

    Use a lambda (requires C#3.0):
    That's the code you see ...
    Since there is no argument (Func<IServiceLocator> has only a return value) you specify this by using ():

    ServiceLocator.SetLocatorProvider( () => { /* return IServiceLocator */ } );
    

    this can be translated to

    ServiceLocator.SetLocatorProvider( () => /* IServiceLocator */ );
    

    Maybe you want to read this question + answer, too.