I am working on implementing a graph class. In class I learned that the breadth-first and depth-first traversals are the same algorithms except to store the traversing nodes a queue and stack is used respectively. So I put all my logic into a Traversal() method which is called by DepthFirstSearch() which passes in a stack as the ADT.
public void DepthFirstSearch(GraphNode<T> root)
{
Stack<GraphNode<T>> s = new Stack<GraphNode<T>>();
Action<GraphNode<T>> insert = s.Push;
Func<GraphNode<T>> retrieve = s.Pop;
//Func<int> stackCount = s.Count; Cannot implicitly convert type 'int' to System.Func<int>' error
Func<int> stackCount = () => s.Count;
Traversal(root, insert, retrieve, stackCount);
}
I am assuming that I cannot pass s.Count into a delegate because it is a class property? So to get around it I used a lambda to closure around that property. But can anyone explain why I need lambda for s.Count but not for s.Pop or s.Push? Thanks.
The reason is because
Stack<T>.PushandStack<T>.Popare already functions that are compatible with the type of delegate (Func<TResult>andAction<T>, whereTResultandTmatch the generic type parameter of yourStack<T>—in your case,GraphNode<T>) to which you’re trying to assign the methods. If they weren’t compatible, you would need to use a lambda function or some other sort of wrapper delegate to assign the method to your delegate variable.While a class property technically consists of a getter and a setter method, in C#, those details are abstracted away, requiring you to wrap a class property in a lambda function. Also, per Servy’s comments below, the compiler wouldn’t be able to easily determine whether you’re trying to assign the getter or the setter to the delegate variable.