Click here to Skip to main content
15,885,768 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
When implementing the following class:
C#
public class MyClass
{
   private readonly int myInt = 4;

   ~MyClass()
   {
      if (myInt != 4)
         throw new Exception();
   }
}

Is it possible for a condition to occur in which the exception will be thrown? Obviously I'm concerned with premature disposal of field values during instance destruction. It'd make sense to me if this were reliable but I'd love to have a second opinion on this.
Posted
Comments
CHill60 28-Jan-13 7:07am    
The behaviour of the exception in the destructor will depend on which version of .NET you are using - a generalisation would be expect your application to terminate. You are better off using the IDisposable pattern
MirageCoder 28-Jan-13 7:23am    
Thanks for your reply, Chill60. So you're saying that I should implement IDisposable, implement the 'myInt'-retrieval in the Dispose()-method, and call the Dispose()-method in the class destructor?
CHill60 28-Jan-13 7:46am    
Absolutely - see Edo's solution for reasons why

1 solution

Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

See this [^] MSDN article


Cheers,
Edo
 
Share this answer
 
v3
Comments
MirageCoder 28-Jan-13 7:30am    
Thanks for the advice Edo, that is definitely something I haven't put any thought into and it justifies my doubts about this implementation style in the first place. I'm going to have to look for a different course of action.

Regardless of the fact that it seems to make sense, can you cite an official source for me where this is explicitly stated?
Joezer BH 28-Jan-13 7:35am    
http://msdn.microsoft.com/en-us/library/aa664609(v=vs.71).aspx
MirageCoder 28-Jan-13 7:41am    
Edo, thank you very much.
Joezer BH 28-Jan-13 7:57am    
NP, I like seeing guys that think deeply into code writing techniques :)
good luck mate

And I give you 5+ on the Q

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900