Generic Addition Required

  • Thread starter Thread starter jehugaleahsa
  • Start date Start date
J

jehugaleahsa

Is there a generic means of adding two values together in C# using the
+ operator?

I would like to be able to write one method for int, double, decimal,
all the other numeric types.

Given that, could the same thing be performed on a string.

Thanks,
Travis
 
Is there a generic means of adding two values together
in C# using the + operator?

No, because System.Object doesn't implement the + operator.
I would like to be able to write one method for int,
double, decimal, all the other numeric types.

I suppose you could do Convert.ToDouble, add those, and cast the
result back. This does not sound very useful. What are you trying to
achieve, more generally?

Eq.
 
No, because System.Object doesn't implement the + operator.


I suppose you could do Convert.ToDouble, add those, and cast the
result back. This does not sound very useful. What are you trying to
achieve, more generally?

Eq.

Essentially, I was hoping there was a way to write an accumulate
method without needed to overload it.
 
Essentially, I was hoping there was a way to write an accumulate
method without needed to overload it.

You are not alone with this wish. Here's an related article on
codeproject and a feature request to ms:
http://www.codeproject.com/csharp/genericnumerics.asp
http://tinyurl.com/2pghky

Here's a sample showing how I worked around this to implement accumulate
in my port of the C++ STL (www.codeplex.com/nstl):

using System.Collections.Generic;

namespace ConsoleApplication11
{
internal delegate Result
BinaryFunction<Arg1, Arg2, Result>(Arg1 lhs, Arg2 rhs);
static class Plus
{
public static BinaryFunction<int, int, int> Int32()
{
return delegate(int lhs, int rhs) { return lhs + rhs; };
}
public static BinaryFunction<string, string, string> String()
{
return delegate(string lhs, string rhs){return lhs + rhs; };
}
}
static class Algorithm
{
public static T
Accumulate<T>(IEnumerable<T> range, T init,
BinaryFunction<T, T, T> binaryOp)
{
foreach(T t in range)
init = binaryOp(init, t);
return init;
}
}
class Program
{
static void Main(string[] args)
{
IEnumerable<int> ints = new int[] {0, 1, 2, 3, 4, 5};
int zero = Algorithm.Accumulate(ints, -15, Plus.Int32());
}
}
}



HTH,
Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top