I have a simple class MyDataClass with a member (obj) that implements IDisposable:
public class MyDataClass : IDisposable
{
private DisposableObject obj;
private List<string> list;
private int c;
public MyDataClass()
{
obj = new DisposableObject();
list = new List<string>();
c = 114;
}
public void Dispose()
{
obj.Dispose();
}
}
public class DisposableObject : IDisposable
{
public void Dispose()
{
// Free resource
Console.WriteLine("Dispose DisposableObject");
}
}
When I run the Code Analysis I get the CA1063 warning which shows me that I should call GC.SuppressFinalize() method in the Dispose() method in MyDataClass implementation.
And I am really confused about this CA1063 warning. Because as far as I know, I should call GC.SuppressFinalize() to indicate to the garbage collector:
“Hey GC, do not worry about this object because I have done already all cleaning work for you!”
So please confirm if I am wrong or not. If I will add the GC.SuppressFinalize() I will get rid of the CA1063 but it will cause that GC will not clean my object. So I will have a memory leak because other class members (managed code) will be not cleaned.
No, your objects will still be collected.
You’re actually only saying: don’t worry about the Finalizer (destructor) of this object. If it has one.
And that is where Code Analysis is getting it wrong: your class does have an
IDisposable.Dispose()method but it does not have a destructor. So the warning is pointless, being over protective and triggering on the wrong reason. Disable or ignore it.