Click here to Skip to main content
Click here to Skip to main content

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

By , 8 Apr 2011
 
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)

About the Author

Chris Trelawny-Ross
Software Developer (Senior) Baylor Healthcare System
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: "By assigning it to a double you are deliberately saying "ge...memberAlbin Abel25 Apr '11 - 7:22 
"By assigning it to a double you are deliberately saying "get rid of all the non-number parts of sub1". I just don't want to allow this option anyway in my code. I know the consequences later. Your solution is still there, It is their choice they use it or not, but they should be aware of this potential problem i.e how to use this manual. That is all about I say. Thanks
GeneralRe: If you want to preserve the other properties of sub1, you sh...memberChris Trelawny-Ross25 Apr '11 - 6:42 
If you want to preserve the other properties of sub1, you shouldn't assign it to a double; you should make dummy a ScorableSubject or a var (which amounts to the same thing).
By assigning it to a double you are deliberately saying "get rid of all the non-number parts of sub1". If you want that data to hang around, don't assign it to a double.
The fact that when you explicitly convert a ScorableSubject to a double you are left only with a double is what compilers do. You should not expect anything different ... and if you want different behavior you should write different code.
GeneralRe: Let us say this is the class. public class ScorableSubj...memberAlbin Abel25 Apr '11 - 6:34 
Let us say this is the class.
public class ScorableSubject
{
public double MarksScored { get; set; }
public string Name{get;set;}
public static implicit operator double(ScorableSubject from)
{
return from.MarksScored;
}
public static implicit operator ScorableSubject(double from)
{
return new ScorableSubject { MarksScored = from };
}
}
}
 
And then I use it like this...
 
ScorableSubject sub1 = new ScorableSubject();
sub1.MarksScored = 50;
sub1.Name = "Maths";
 
double dummy = sub1;
 
ScorableSubject sub2 = (ScorableSubject)dummy;
MessageBox.Show(sub2.Name);
 
What will be sub2.Name?
GeneralRe: Hmmm. Ok. Thanks for telling. :thumbsup:mvpSandeep Mewara24 Apr '11 - 23:05 
Hmmm. Ok. Thanks for telling. Thumbs Up | :thumbsup:
GeneralHi I was trying to use this solution but then found a very p...memberAlbin Abel24 Apr '11 - 22:54 
Hi I was trying to use this solution but then found a very potential problem. As you said "I'm too long in the tooth of strongly typed languages ", where your solution 100% violate this. As you implemented your object is no more typed. For example
 
ScorableSubject subject1 = new ScorableSubject();
subject1.MarksScored = 50;
 
double dummy = subject1;
Here a great risk that the object degraded to a value type and not typed any more. Where as the above solution CommonArithmatic object is not convertible in such a way unless the conversion logic defined inside it. So I am still stick to the dynamic object in this case.
GeneralRe: Virtually upvoted it. :)mvpSandeep Mewara24 Apr '11 - 23:06 
Virtually upvoted it. Smile | :)
GeneralRe: Albin, I'm not sure what I violated: my object is still str...memberChris Trelawny-Ross25 Apr '11 - 4:35 
Albin,
 
I'm not sure what I violated: my object is still strongly typed. When you assign to a variable of type double (your 'dummy') you are not 'degrading' the object to a value type. If you want 'dummy' to still be a ScorableSubject, you should type it as ScorableSubject, or var. Typing dummy as double tells the compiler that you specfically want to convert subject1 to a double. This is not 'degrading' the object, its a very deliberate conversion that you are asking the compiler to do for you. And please note that 'dummy' is, in fact, still typed. Just because it is a value type does not mean it has no type. Value types are just as much types as class types are!
GeneralReason for my vote of 5 Excellent refactoring to a lucid exp...memberMacMaverick10 Apr '11 - 22:18 
Reason for my vote of 5
Excellent refactoring to a lucid expostion of the principle. Nothing like 100 -> 5 , hehe
GeneralRe: Hi MacMaverick this solution has a problem which is not advi...memberAlbin Abel24 Apr '11 - 22:56 
Hi MacMaverick this solution has a problem which is not advisable unless otherwise fixed. Look at my comment.
GeneralReason for my vote of 5 Nice Idea! My 5mvpRaviRanjankr6 Apr '11 - 9:58 
Reason for my vote of 5
Nice Idea! My 5

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 8 Apr 2011
Article Copyright 2011 by Chris Trelawny-Ross
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid