0

I need to overload operator >=. If the condition is true, the operator returns true, otherwise false. If at least one of the objects is null – throw an exception (ArgumentException). I tried this. What's wrong?

public static bool operator false(Staff inputPerson) { if ((inputPerson.salary) <= 15000) { return true; } else if ((inputPerson.salary) is null) { throw new ArgumentOutOfRangeException("This person does not have a job"); } return false; } 
3
  • 1
    You are not overloading >= in the above method. Commented Nov 10, 2014 at 16:29
  • 1
    Why are you trying to do this? Comparing to staff members like staffA >= staffB doesn't make any sense and it makes the code cryptic. staffA.Salary >= staffB.Salary is a lot cleaner. Commented Nov 10, 2014 at 16:48
  • @xxbbcc does indeed have a valid point. When you are overloading an operator you do need to ask if your comparison makes sense. Salary alone does not appear to be a good candidate for comparing two staff objects. Commented Nov 10, 2014 at 20:07

2 Answers 2

3

You need to do something like public static bool operator <= (Rational rational1, Rational rational2)

When you overload this, you need to ensure that you overload all the related operators too. e.g. <, > <=, >= etc. as well as the equality operators and methods.

You need to pass in both of the objects to be compared, as the method is static, and not an instance method.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the comment about overloading all the operators.
Can you edit this question. I was on my phone and accidentally downvoted and it won't let me remove the downvote.
Sorry about that. I have edited it to +1. Got to be more careful on my phone lol.
0

Try this:

public static bool operator >=(Staff p1, Staff p2) { if (p1 is null || p2 is null) { throw new ArgumentOutOfRangeException("This person does not have a job"); } return p1.salary >= p2.salary; } 

Source: http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx

3 Comments

>= would return a bool.
Why would >= return a Staff object instead of a bool?
Oups. Copy and paste mistake. Fixed. Thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.