Search code examples
c#dispose

Why I am getting error when using Dispose() in C#


I am trying to dispose of the object in c#. But when I use the Dispose() method I am getting an error. I have mentioned my tried code below.

Tried code:

public class ParentModel : ParentModelBase, IDisposable
  {

     protected override void OnDispose()
        {
            createdObject.PageMaximizedViewModel = null;
            createdObject = null;
            createdObject.Dispose();
            base.OnDispose();
        }
  }

Error:

‘ParentCreatedClass’ does not contain a definition for ‘Dispose’ and no accessible extension method ’Dispose’ accepting a first argument of type ‘ParentCreatedClass’ could be found(are you missing a using directive or an assembly reference?) Can not resolve symbol ‘Dispose’

I am struggling with these hours. How can I solve this problem?


Solution

  • ParentCreatedClass simply doesn't have a public Dispose() method - you can't call a method that don't exist....

    Apparently, the ParentCreatedClass either doesn't implement the IDisposable interface, or it implements it explicitly, which means you must first cast it to IDisposable before you can call Dispose() on it - so try this:

    protected override void OnDispose()
    {
        createdObject.PageMaximizedViewModel = null;
        ((IDisposable)createdObject).Dispose(); 
        base.OnDispose();
    }
    

    Here's an online demo.

    Also, Even if this code would have compiled, you're calling .Dispose() (or any other method for that matter) after assigning null to the reference will cause a NullReferenceException - remove the createdObject = null; line from your code. It's useless.