Tuesday, June 12, 2007

Error: Do not override object.Finalize. Instead, provide a destructor.

You cannot call or override the Object.Finalize method from the C#. Because C# provides destructors as the mechanism for writing finalization code. You must use the destructor syntax in C# to perform cleanup operations. This syntax is convenient because it implicitly calls the Finalize method for an object's base class. This guarantees that Finalize is called for all levels of destructors from which the current class is derived.

Suppose you have written a destructor in your code, like this:

~DemoClass()
{
// Perform some cleanup operations here.
}

This code implicitly translates to the following:

protected override void Finalize()
{
try
{
// Perform some cleanup operations here.
}
finally
{
base.Finalize();
}
}

So if you have a destructor in your class and your are also trying to override Finalize function then you wil l get following build error.

"Type already defines a member called 'Finalize' with the same parameter types."

3 comments:

Anonymous said...

thx man, used this today.

Yogesh said...

Thx dude, helped me today. Learned this new thing for the day!

Anonymous said...

thks brow