Solved

Seeking an explanation of what "Action" does in this method?

Posted on 2012-03-28
3
381 Views
Last Modified: 2012-03-28
I'm very new to the Action delegate and have no idea what is going on here. Could someone please explain what could be the purpose of putting "Action" here? Is this somehow related to a "pass by reference"?
public void Traverse(Action<Node> v)
{
   v(this);
   foreach (var c in Children) //Children being a property that returns ReadOnlyCollection containing a List<Node>
   {
      c.Traverse(v);
   }
}

Open in new window

0
Comment
Question by:Eindoofus
  • 2
3 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 37779930
Action is a type, and it can be thought of like a pointer to a function that has no return value (i.e. returns void). The counterpart to Action for functions which do return values is Func.

Action is delegate type. You can execute an instance of a delegate as if it were an actual function (this is what line 3 in your snippet is doing).

The net effect of your code is that you can pass in the name of any function (within scope) that accepts a parameter of type Node and which returns nothing. Inside of Traverse, this function will be executed at line 3, passing the reference to the current class (which is assumed be Node) to the target function as its parameter.
0
 

Author Comment

by:Eindoofus
ID: 37779974
Thanks. Btw, can this be considered a recursive method?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37779987
Yes, because it calls itself (line 6).

Also, I just saw the part of your question regarding "pass-by-reference". Action is a class, so it would be pass-by-reference. All classes are passed by reference. Value types (including structs) are passed by value.
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question