Wednesday, August 18, 2004

Interesting See Sharp

Here I am going to talk about interesting things I learnt about C#.

1) Using statement - to automatically call dispose method of an object

using (Class1 obj = New Class1)
{
obj.SomeMethod();
}
equivalent to
Class1 obj = new Class1
try{obj.SomeMethod(); }
finally{ obj.Dispose(); }

2) Boolean is not equal to Integer in C#

helpful in case of unintentional assignment in a boolean expression

if( a = 2) {} -- compiler will give an error message.

3) Finalize Vs Dispose?

Dispose() is an explicit way to perform cleanup of objects (if it is called, then you should suppress GC from calling Finalize() using GC.SuppressFinalize(this); (Note: the class should implement IDisposable interface)

~MyClass() (destructor) will be called by GC
the compiler actually translates it to

protected override void Finalize()
{
try { // do work here }
finally { base.Finalize(); }
}

why do you need them?
The reason is, Dispose() needs be called explicitly. So if the programmer forgets to call Dispose() or due to some exception in other code, Dispose() doesnt get called, then?

But if you implement Finalize/Destructor, then altleast after a while (when the object will be collected by GC), those system resources will be freed.

4) All right, now why do you need to call Close() and Dispose() on Connection object?
Especially in ADO.Net Connection object, the practice is to use con.Close() and con.Dispose()?

5) How about Form.Dispose and Form.Close()?
The difference between Form.Dispose and Form.Close is large: Dispose destroy the object, and Close simply close the form (send message - WM_CLOSE), without destroy.


0 Comments:

Post a Comment

<< Home