This class is a very simple and elegant example of using an implicit operator. It is very common to test for the result of a function call and if not successful to provide further detail via a second call. However instead of having to detect an error then going back to fetch the error based on a code as a separate call, this class provides a mechanism though which you can seamlessly attach a message to a boolean result. A good example of usage would be in authentication logic.
Namespace:
CA.CommonAssembly: CA.Common (in CA.Common.dll) Version: 1.0.0.0 (1.0.0.0)
Remarks
A typical example of this function would be returning a result from an authentication function. The authentication function can return a result indicating if the result was successful or not. In addition a message can be included with the result for example the password is about to expire or if it is a failure then it can include the why the authentication failed.
Examples
//Source code from the Code Associate C# code library, Full documentation and latest updates can be found //@ http://www.codeassociate.com/caapi/ using System.Diagnostics; using NUnit.Framework; namespace CA.Common.UnitTest { [TestFixture] public class BoolResultMessage_UnitTests { private BoolResultMessage MimikBoolFunction(bool returnvalue) { BoolResultMessage result = new BoolResultMessage(); result.Success = returnvalue; result.Message = string.Format("The result of BoolResultMessage is {0}", returnvalue.ToString()); return result; } [Test] public void TestBoolResultMessage() { // create a BoolResultMessage.. this would typically be the return of a function the function above mimiks a business type function BoolResultMessage result = MimikBoolFunction(false); // There are 3 tests to do.. //1 test the result of Success Property without using the implicit operator Assert.AreEqual(false, result.Success); //2 test the implicit operator manually by doing a Manual cast of the result to a bool Assert.AreEqual(false, (bool)result); //3 finally the most useful we have the implicit conversion done for us.. note result is a BoolResultMessage struct not a boolean Assert.IsFalse(result); // the business module would be typically ad additional information to a false return value.. // for example if the login failed, the message could contain some information as to why is security allowed it? (locked, user not valid, password not valid, expired etc) if (!result) { // becuase the result was false lets write some data out System.Diagnostics.Debug.WriteLine(result.Message); } // now test the true value result = MimikBoolFunction(true); Assert.IsTrue(result); } [Test] public void ExampleMockAuthenticationTypeFunctionUsingBoolResultMessage() { // this creates a mock message witht a false result. BoolResultMessage result = MimikBoolFunction(false); if (result) { // do normal code } else { Trace.WriteLine(string.Format("The Authentication failed with message '{0}'", result.Message)); } } } }