Real world example of C# Anonymous Methods

Often when a new language features come out (in this case anonymous method) we often see syntax examples like this:

delegate void SomeDelegate();  
public void InvokeMethod()  
{  
    SomeDelegate del = delegate()   
    {  
        MessageBox.Show("Hello");  
    };  
    del();   
}  

and we say, great but when is code like THAT ever going to be useful to me? In that trivial example, of course that's not very useful. But when you consider the power anonymous methods gives you both to pass in parameters and also make use of local objects then tons of possibilities are opened up for making code more concise and efficient. Consider a case where you're using a DataReader to read multiple result sets. Your code might look something like this:

public Person GetPerson(int personID)  
{  
    //(Perform data access code here to create DataReader)  
    Person person = new Person();  
      
    if (dr.Read())  
    {  
        person = personMapper.BuildItem(dr);  
    }  
      
    dr.NextResult();  
    if (dr.Read())  
    {  
        person.Address = addressMapper.BuildItem(dr);  
    }  
      
    dr.NextResult();  
    if (dr.Read())  
    {  
        person.EmploymentInfo = employmentMapper.BuildItem(dr);  
    }  
}

This code is now littered with IF statements and dr.NextResult() method calls. To make this more concise, you could create a simple method that passes in a delegate that you can use anonymously:

public static void ReadNextResult(NullableDataReader dr, Execute execute)  
{  
    dr.NextResult();  
    if (dr.Read())  
    {  
        execute();  
    }  
}

Then the consuming code can simply look like this:

public Person GetPerson(int personID)  
{  
    //(Perform data access code here to create DataReader)  
    Person person = new Person();  
      
    DataUtil.ReadNextResult(dr, delegate()  
        { person = personMapper.BuildItem(dr); });

    DataUtil.ReadNextResult(dr, delegate()  
        { person.Address = addressMapper.BuildItem(dr); });

    DataUtil.ReadNextResult(dr, delegate()  
        { person.EmploymentInfo = employmentMapper.BuildItem(dr); });  
}

Notice that because of the use of anonymous methods, not only can we pass in the DataReader to the method but also we can use local objects (e.g., the "mapper" objects) inside the anonymous methods. Internally the C# compiler creates private nested classes containing the delegates we want to execute that have member variables that are assigned the "local object" references which is why it's possible to pull this off in-line rather than having to create a completely separate method.

Tweet Post Share Update Email RSS