0

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?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • It's not instead of a method signature, those using-blocks are the method signature. Using-Blocks are shorthands for the dispose pattern, calling dispose after they finished or failed. – Christoph Sonntag Jan 02 '19 at 11:20
  • Possible duplicate of [Delegates in C#](https://stackoverflow.com/questions/1735203/delegates-in-c-sharp) – R Pelzer Jan 02 '19 at 11:22
  • See this documentation - https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ms439682(v%3Doffice.14) - it states the requirement for the syntax – PaulF Jan 02 '19 at 11:22
  • And 'using' block is used to handle lifetime of unmanaged objects. See this link. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement – Nilesh Shinde Jan 02 '19 at 11:27

1 Answers1

5

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);
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 2
    Right. And the "using" keyword is to instanciate a IDisposable object, telling the CLR to automatically dispose it at the end of the closure... Cheers ;) – Leogiciel Jan 02 '19 at 11:23