C#
  Home arrow C# arrow Page 2 - Methods in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Methods in C#
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-10-02

    Table of Contents:
  • Methods in C#
  • Outer Variables
  • Anonymous Methods
  • try Statements and Exceptions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Methods in C# - Outer Variables


    (Page 2 of 4 )

    A lambda expression can reference the local variables and parameters of the method in which it’s defined. For example:

      delegate int NumericSequence ();

      class Test
      {
        static void Main()
        {
         
    int seed = 0;
          NumericSequence natural = () => seed++;
          Console.WriteLine (natural());                                    // 0
          Console.WriteLine (natural());    // 1
        }
      }

    Local variables and parameters referenced by a lambda expression are called outer variables. In our example,seedis an outer variable referenced by the lambda expression() => seed++. Outer variables are captured, meaning their lifetime is extended to that of the lambda expression. Let’s refactor the example to make the effect of capturing more striking:

      delegate int NumericSequence ();

      class Test
     
    {
        static NumericSequence Natural ()
        {
         
    int seed = 0;        // executes once (per call to Natural())
          return () => seed++; // executes twice (per call to delegate instance
                               //
    returned by Natural())
        }

        static void Main()
       
    {
          NumericSequence natural = Natural ();
          Console.WriteLine (natural());      // 0
          Console.WriteLine (natural());      // 1
       
    }
      }

    The local variableseedwould ordinarily just pop off the stack when theNaturalmethod exits. However,seedis captured by the lambda expression of the delegate instance returned byNatural. This means the lifetime ofseedis extended to the lifetime of that delegate instance. Subsequent invocations of that same delegate instance will reuse the sameseed variable.

    Capturing is internally implemented by “lifting” the captured variables into fields of a private class. When the method is called, the class is instantiated and lifetime-bound to the delegate instance.

    A local variable instantiated within a lambda expression is unique per invocation of the delegate instance. If we refactor our previous example to instantiateseedwithin the lambda expression, we get a different (in this case, undesirable) result:

      delegate int NumericSequence ();

      class Test
     
    {
        static NumericSequence Natural ()
        {
         
    return () => {int seed = 0; return seed++; };
        }

        static void Main()
       
    {
          NumericSequence natural =
    Natural ();
          Console.WriteLine
    (natural());                      // 0   
          Console.WriteLine
    (natural());                      // 0
        }
      }

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 in a Nutshell, Third Edition, A...
     

    Buy this book now. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT