Click here to Skip to main content
16,013,605 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys!
When I declared some code in C#:
C#
public class MyClass
    {
    public MyClass()
        {
        }

    //Destructor
    ~MyClass()
        {
        Console.WriteLine("Object destroied");
        }

    }

public static void main(string[] arg)
    {
    MyClass class_A = new MyClass();
    DoWork();
    }

public static void DoWork()
    {
    MyClass class_B = new MyClass();
    }


/////////////////////////////////////

Why "class_B" object run out DoWork function! I don't run into its ~MyClass().
When main performed finish. two objects "class_A" and "class_B" run into ~MyClass();

Can anyone explain for me!! Thanks for your time...


[edit]Code block added, indentation added and syntax errors corrected - OriginalGriff[/edit]
Posted
Updated 30-Mar-13 22:30pm
v2
Comments
OriginalGriff 31-Mar-13 4:32am    
I have fixed the compilation errors in your fragment (spelling of "public", placement of "[]" in args definition) - please copy and paste your code in future, that way you know that what you tested to show the problem is exactly what you show us! :laugh:

Basically, I suspect the problem is that your code isn't running!
I copied your code into a console app and tried it:
C#
class Program
    {
    public static void Main(string[] arg)
        {
        MyClass class_A = new MyClass();
        DoWork();
        }

    public static void DoWork()
        {
        Console.WriteLine("In Do work");
        MyClass class_B = new MyClass();
        }
    }
public class MyClass
    {
    public MyClass()
        {
        }

    //Destructor
    ~MyClass()
        {
        Console.WriteLine("Object destroied");
        }

    }
And sure enough, using the debugger I could see that the destructor method was indeed called twice.

Did you really call your method "main"? Or did you use "Main"? C# is case sensitive, so the former would not be run automatically.
 
Share this answer
 
Object allocation and disposals are much different in managed code. That is objects are destroyed by garbage collection mechanism that is not always predictable as you expected. In this case destructors are only called after code has finished. Please refer to [^] for more details.
 
Share this answer
 

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