The objective is to create a simple program that calculates the sum of pre-processed set. The Sum
must be generic to allow it accepts both integer and floating point set.
The following code does not compile. Could you tell me how to fix it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
static class Program
{
delegate T del<T>(T x);
static T Sum<T>(del<T> df, IEnumerable<T> data)
{
T s = 0;
foreach (var x in data) s += df(x);
return s;
}
static void Main(string[] args)
{
var data = Enumerable.Range(1, 4);
int sum = Sum<int>(x => x * x, data);
Console.WriteLine(sum);
}
}
}
Error Messages (roughly speaking):
- cannot convert
int
toT
. +=
is not available forT
.