Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
Me either. See here in the C# Language Reference. This means you can overload the operators for your classes. The example on MSDN talks about classes that have a true, false, or null (neither true nor false) state. You could also create a type that can be both true and false.
Overloading operators can lead to code that is difficult to read. You should only overload operators when it makes sense to do it. If it is unclear what “if (myType)” means, don’t overload the operators.
I wrote a small rules engine for a company a while back and this would have been helpful. Supplemental rules were implemented as separate classes so that they could be dynamically strung together in different orders as the business logic changed.
Here’s a contrived sample using the true/false operators:
public class Customer { public string CustomerName { get; set; } public string EmailAddress { get; set; } public decimal OutstandingBalance { get; set; } } public class CustomerIsGoodRule { public CustomerIsGoodRule(Customer customer) { this.Customer = customer; } Customer Customer { get; set; } public static bool operator true(CustomerIsGoodRule theCustomer) { return (theCustomer.Customer.OutstandingBalance <= 0); } public static bool operator false(CustomerIsGoodRule theCustomer) { return (theCustomer.Customer.OutstandingBalance > 0); } } class Program { static void Main(string[] args) { Customer c = new Customer(); c.CustomerName = "Joanne Doe"; c.EmailAddress = "joannedoe@mailinator.com"; c.OutstandingBalance = 25; CustomerIsGoodRule cigr = new CustomerIsGoodRule(c); if (cigr) { SendNewCatalog(); } else { SendNewStatement(); } } }
One thing to keep in mind is that if you provide a definition for true, you must also provide one for false. Also notice that the logical negation operator (!) was not overriden, so a statement like if (!cigr) fails to compile.