AndreaNobili
AndreaNobili

Reputation: 42957

What is the exact meaning of this example using delegate()?

I am not so into C# (I came from Java) and I have the following doubts about how exactly works the delegate methods related to this example:

List<string> urlList = IndirizziProtocolliSQL.GetListaIndirizziSiti(dbConfig);

foreach (string currentUrl in urlList)
{
    Debug.Print("Current url: " + currentUrl);

    SPSecurity.RunWithElevatedPrivileges(delegate ()
    {
        using (SPSite oSiteCollection = new SPSite(currentUrl))
        {
            using (SPWeb oWebsite = oSiteCollection.OpenWeb())
            {
            }
        }
    });
}

From what I can understand reading the official documentation: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/

the delegate() is used to pass a method as input parameter of another method.

For example if I have something like:

public delegate int MyDelegate (string s);

it means is a reference to any method having the signature of this method (return type, method name, in put parameters).

If it is correct, what exactly means my first original example? Why instead a method signature I have a using(...){...} block?

What is the exact meaning of this syntax?

Upvotes: 0

Views: 83

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156978

The delegate () { } just indicates an anonymous inline method / delegate is passed into the function. The body of that method is just like any C# code block, and can contain using statements, or any other statement.

This would be similar to:

private void Method()
{
    using (SPSite oSiteCollection = new SPSite(currentUrl))
    {
        using (SPWeb oWebsite = oSiteCollection.OpenWeb())
        {
        }
    }
});

SPSecurity.RunWithElevatedPrivileges(Method);

Upvotes: 5

Related Questions