Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to perform arithmetic operations between any objects by inheriting a common arithmetic parent class in .NET 4.

5.00/5 (4 votes)
8 Apr 2011CPOL 22.2K  
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...
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 };
            }
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)