<p>I have a "Status" class in C#, used like this:</p>

<pre><code>Status MyFunction()
{
   if(...) // something bad
     return new Status(false, "Something went wrong")
   else
     return new Status(true, "OK");
}
</code></pre>

<p>You get the idea.
All callers of MyFunction <em>should</em> check the returned Status:</p>

<pre><code>Status myStatus = MyFunction();
if ( ! myStatus.IsOK() )
   // handle it, show a message,...
</code></pre>

<p>Lazy callers however can ignore the Status.</p>

<pre><code>MyFunction(); // call function and ignore returned Status
</code></pre>

<p>or </p>

<pre><code>{
  Status myStatus = MyFunction(); 
} // lose all references to myStatus, without calling IsOK() on it
</code></pre>

<p>Is it possible to make this impossible? e.g. an throw exception</p>

<p><strong>In general</strong>: is it possible to write a C# class on which you <em>have</em> to call a certain function?</p>

<p>In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the <em>destructor</em> and ring some bells when someone doesn't check this instance.</p>

<p>What is the equivalent option in C#?
I read somewhere that "You don't want a destructor in your C# class"</p>

<p>Is the Dispose method of the IDisposable interface an option?</p>

<p>In this case there are no unmanaged resources to free.
Additionally, it is not determined <em>when</em> the GC will dispose the object.
When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance?
The "using" keyword does help, but again, it is not <em>required</em> for lazy callers.</p>

[{'answer_id': 19560, 'author': 'Ian Nelson', 'author_id': 2084, 'author_profile': 'https://Stackoverflow.com/users/2084', 'pm_score': 3, 'selected': False, 'text': '<p>I know this doesn\'t answer your question directly, but if "something went wrong" within your function (unexpected circumstances) I think you should be throwing an exception rather than using status return codes.</p>\n\n<p>Then leave it up to the caller to catch and handle this exception if it can, or allow it to propogate if the caller is unable to handle the situation.</p>\n\n<p>The exception thrown could be of a custom type if this is appropriate.</p>\n\n<p>For <em>expected</em> alternative results, I agree with @Jon Limjap\'s suggestion.  I\'m fond of a bool return type and prefixing the method name with "Try", a la:</p>\n\n<pre><code>bool TryMyFunction(out Status status)\n{\n}\n</code></pre>\n'}, {'answer_id': 19561, 'author': 'TK.', 'author_id': 1816, 'author_profile': 'https://Stackoverflow.com/users/1816', 'pm_score': 0, 'selected': False, 'text': '<p>You can throw an exception by:</p>\n\n<pre><code>throw MyException;\n\n\n[global::System.Serializable]\n        public class MyException : Exception\n        {\n        //\n        // For guidelines regarding the creation of new exception types, see\n        //    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp\n        // and\n        //    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp\n        //\n\n        public MyException () { }\n        public MyException ( string message ) : base( message ) { }\n        public MyException ( string message, Exception inner ) : base( message, inner ) { }\n        protected MyException (\n          System.Runtime.Serialization.SerializationInfo info,\n          System.Runtime.Serialization.StreamingContext context )\n            : base( info, context ) { }\n    }\n</code></pre>\n\n<p>The above exception is fully customizable to your requirements.</p>\n\n<p>One thing I would say is this, I would leave it to the caller to check the return code, it is their responsability you just provide the means and interface. Also, It is a lot more efficient to use return codes and check the status with an if statement rather than trhowing exceptions. If it really is an <em>Exceptional</em> circumstance, then by all means throw away... but say if you failed to open a device, then it might be more prudent to stick with the return code.</p>\n'}, {'answer_id': 19569, 'author': 'fulmicoton', 'author_id': 446497, 'author_profile': 'https://Stackoverflow.com/users/446497', 'pm_score': 0, 'selected': False, 'text': "<p>That would sure be nice to have the compiler check that rather than through an expression. :/\nDon't see any way to do that though...</p>\n"}, {'answer_id': 19572, 'author': 'Auron', 'author_id': 1679, 'author_profile': 'https://Stackoverflow.com/users/1679', 'pm_score': 1, 'selected': False, 'text': '<p>Using Status as a return value remembers me of the "old days" of C programming, when you returned an integer below 0 if something didn\'t work. </p>\n\n<p>Wouldn\'t it be better if you throw an exception when (as you put it) <em>something went wrong</em>? If some "lazy code" doesn\'t catch your exception, you\'ll know for sure.</p>\n'}, {'answer_id': 19586, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 2, 'selected': False, 'text': '<p>Even System.Net.WebRequest throws an exception when the returned HTTP status code is an error code. The typical way to handle it is to wrap a try/catch around it. You can still ignore the status code in the catch block.</p>\n\n<p>You could, however, have a parameter of Action&lt; Status> so that the caller is forced to pass a callback function that accepts a status and then checking to see if they called it.</p>\n\n<pre><code>void MyFunction(Action&lt;Status&gt; callback)\n { bool errorHappened = false;\n\n   if (somethingBadHappend) errorHappened = true;\n\n   Status status = (errorHappend)\n                     ? new Status(false, "Something went wrong")\n                     : new Status(true, "OK");\n   callback(status)\n\n   if (!status.isOkWasCalled) \n     throw new Exception("Please call IsOK() on Status"). \n }\n\nMyFunction(status =&gt; if (!status.IsOK()) onerror());\n</code></pre>\n\n<p>If you\'re worried about them calling IsOK() without doing anything, use Expression&lt; Func&lt; Status,bool>> instead and then you can analyse the lambda to see what they do with the status:</p>\n\n<pre><code>void MyFunction(Expression&lt;Func&lt;Status,bool&gt;&gt; callback)\n { if (!visitCallbackExpressionTreeAndCheckForIsOKHandlingPattern(callback))\n     throw new Exception\n                ("Please handle any error statuses in your callback");\n\n\n   bool errorHappened = false;\n\n   if (somethingBadHappend) errorHappened = true;\n\n   Status status = (errorHappend)\n                     ? new Status(false, "Something went wrong")\n                     : new Status(true, "OK");\n\n   callback.Compile()(status);\n }\n\nMyFunction(status =&gt; status.IsOK() ? true : onerror());\n</code></pre>\n\n<p>Or forego the status class altogether and make them pass in one delegate for success and another one for an error:</p>\n\n<pre><code>void MyFunction(Action success, Action error)\n { if (somethingBadHappened) error(); else success();\n }\n\nMyFunction(()=&gt;;,()=&gt;handleError()); \n</code></pre>\n'}, {'answer_id': 19590, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 3, 'selected': False, 'text': "<p>If you really want to require the user to retrieve the result of MyFunction, you might want to void it instead and use an out or ref variable, e.g.,</p>\n\n<pre><code>void MyFunction(out Status status)\n{\n}\n</code></pre>\n\n<p>It might look ugly but at least it ensures that a variable is passed into the function that will pick up the result you need it to pick up.</p>\n\n<p>@Ian,</p>\n\n<p>The problem with exceptions is that if it's something that happens a little too often, you might be spending too much system resources for the exception. An exception really should be used for <em>exceptional</em> errors, not totally expected messages.</p>\n"}, {'answer_id': 19591, 'author': 'pauldoo', 'author_id': 755, 'author_profile': 'https://Stackoverflow.com/users/755', 'pm_score': 0, 'selected': False, 'text': '<p>GCC has a <a href="http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html" rel="nofollow noreferrer"><code>warn_unused_result</code></a> attribute which is ideal for this sort of thing.  Perhaps the Microsoft compilers have something similar.</p>\n'}, {'answer_id': 19599, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 0, 'selected': False, 'text': '<p>@Paul you could do it at compile time with <a href="http://www.google.com/search?hl=en&amp;rls=com.microsoft%3Aen-us&amp;q=%22extensible+C%23%22" rel="nofollow noreferrer">Extensible C#</a>.</p>\n'}, {'answer_id': 19661, 'author': 'kemiller2002', 'author_id': 1942, 'author_profile': 'https://Stackoverflow.com/users/1942', 'pm_score': 1, 'selected': False, 'text': "<p>Instead of forcing someone to check the status, I think you should assume the programmer is aware of this risks of not doing so and has a reason for taking that course of action.  You don't know how the function is going to be used in the future and placing a limitation like that only restricts the possibilities.</p>\n"}, {'answer_id': 19835, 'author': 'Weeble', 'author_id': 2283, 'author_profile': 'https://Stackoverflow.com/users/2283', 'pm_score': 3, 'selected': True, 'text': '<p>I am fairly certain you can\'t get the effect you want as a return value from a method. C# just can\'t do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following:</p>\n\n<pre><code>using System;\n\npublic class Example\n{\n    public class Toy\n    {\n        private bool inCupboard = false;\n        public void Play() { Console.WriteLine("Playing."); }\n        public void PutAway() { inCupboard = true; }\n        public bool IsInCupboard { get { return inCupboard; } }\n    }\n\n    public delegate void ToyUseCallback(Toy toy);\n\n    public class Parent\n    {\n        public static void RequestToy(ToyUseCallback callback)\n        {\n            Toy toy = new Toy();\n            callback(toy);\n            if (!toy.IsInCupboard)\n            {\n                throw new Exception("You didn\'t put your toy in the cupboard!");\n            }\n        }\n    }\n\n    public class Child\n    {\n        public static void Play()\n        {\n            Parent.RequestToy(delegate(Toy toy)\n            {\n                toy.Play();\n                // Oops! Forgot to put the toy away!\n            });\n        }\n    }\n\n    public static void Main()\n    {\n        Child.Play();\n        Console.ReadLine();\n    }\n}\n</code></pre>\n\n<p>In the very simple example, you get an instance of Toy by calling Parent.RequestToy, <em>and passing it a delegate</em>. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all "something went wrong" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request.</p>\n'}, {'answer_id': 26170051, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 0, 'selected': False, 'text': "<p>One pattern which may sometimes be helpful if the object to which code issues requests will only be used by a single thread(*) is to have the object keep an error state, and say that if an operation fails the object will be unusable until the error state is reset (future requests should fail immediately, preferably by throwing an immediate exception which includes information about both the previous failure and the new request).  In cases where calling code happens to anticipate a problem, this may allow the calling code to handle the problem more cleanly than if an exception were thrown; problems which are not ignored by the calling code will generally end up triggering an exception pretty soon after they occur.</p>\n\n<p>(*) If a resource will be accessed by multiple threads, create a wrapper object for each thread, and have each thread's requests go through its own wrapper.</p>\n\n<p>This pattern is usable even in contexts where exceptions aren't, and may sometimes be very practical in such cases.  In general, however, some variation of the try/do pattern is usually better.  Have methods throw exception on failure unless the caller explicitly indicates (by using a <code>TryXX</code> method) that failures are expected.  If callers say failures are expected but don't handle them, that's their problem.  One could combine the try/do with a second layer of protection using the scheme above, but I'm not sure whether it would be worth the cost.</p>\n"}]
['https://Stackoverflow.com/questions/19553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1163/']