Click here to Skip to main content
11,504,184 members (73,701 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
When implementing the following class:
public class MyClass
   private readonly int myInt = 4;
      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 28-Jan-13 0:40am
CHill60 at 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
Hoogdraaed at 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 at 28-Jan-13 7:46am
Absolutely - see Edo's solution for reasons why

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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

Hoogdraaed at 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?
Edo Tzumer at 28-Jan-13 7:35am
Hoogdraaed at 28-Jan-13 7:41am
Edo, thank you very much.
Edo Tzumer at 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)

  Print Answers RSS
0 OriginalGriff 230
1 Sergey Alexandrovich Kryukov 228
2 CHill60 195
3 DamithSL 150
4 Peter Leow 145
0 Sergey Alexandrovich Kryukov 698
1 Maciej Los 435
2 Peter Leow 420
3 DamithSL 395
4 OriginalGriff 357

Advertise | Privacy | Mobile
Web03 | 2.8.150520.1 | Last Updated 28 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100