You got me thinking about other ways to accomplish "objects that are not numbers honoring math operators without implementing the operators on the objects."
I'm too long in the tooth of strongly typed languages to have a good comfort level with all things dynamic (although reading about the
BinaryOperationBinder
has raised my curiosity level!), so I thought I'd look for a non-dynamic way to accomplish your goal. It will also help readers who are not able to use .NET 4.0.
I first tried to use extension methods, but it seems you can't implement an operator as an extension method.
But... you can implement casts between objects and numeric types. So, here is a solution that allows non-numeric objects to cleanly participate in numeric expressions:
namespace ObjectMathOperations
{
class Program
{
static void Main(string[] args)
{
ScorableSubject math = 95.3;
ScorableSubject science = 97;
double totalScore = math + science;
}
}
public class ScorableSubject
{
public double MarksScored { get; set; }
public static implicit operator double(ScorableSubject from)
{
return from.MarksScored;
}
public static implicit operator ScorableSubject(double from)
{
return new ScorableSubject { MarksScored = from };
}
}
}