I have the following code that does something very simple: it visits the Node object tree recursively and calculates the sum of the property named Info.
using System;
namespace ConsoleApplication11
{
static class Program
{
static void Main(string[] args)
{
var node = new Node {Info = 1, Left = new Node {Info = 1}};
Console.WriteLine(node.Sum());
Console.ReadLine();
}
static int Sum(this Node node)
{
return node.Info + (node.Left == null ? 0 : Sum(node.Left)) + (node.Right == null ? 0 : Sum(node.Right));
}
}
public class Node
{
public int Info { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
}
The best solution would be
using System;
namespace ConsoleApplication11
{
static class Program
{
static Func<Node, int> fSum = (node) => node.Info + (node.Left == null ? 0 : fSum(node.Left)) + (node.Right == null ? 0 : fSum(node.Right));
static void Main(string[] args)
{
var node = new Node {Info = 1, Left = new Node {Info = 1}};
Console.WriteLine(fSum(node));
Console.ReadLine();
}
}
public class Node
{
public int Info { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
}
My problem and question: why can't I have a function inside a method? I get an error: using the unassigned local variable 'fSum'
using System;
namespace ConsoleApplication11
{
static class Program
{
static void Main(string[] args)
{
Func<Node, int> fSum = (node) => node.Info + (node.Left == null ? 0 : fSum(node.Left)) + (node.Right == null ? 0 : fSum(node.Right));
var n = new Node {Info = 1, Left = new Node {Info = 1}};
Console.WriteLine(fSum(n));
Console.ReadLine();
}
}
public class Node
{
public int Info { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
}
user407665
source
share