[C#] Calling Destroy() in a custom class destructor

When trying to call Destroy on a GameObject which is a member of my custom class, in the class destructor, I get the following error :

“Destroy can only be called from the main thread”

 public class myClass {
    
    GameObject go;
    
    public myClass()
    {
    go = GameObject.Instantiate(...); 
    }
    
    ~myClass()
    {
    Destroy(go);
    }
    
    }

I have a class extending Monobehaviour to act as the “main” using its Update() function.
If I set my custom class to null in the main loop, the destructor is called but it can’t use Destroy() on the gameObject and thus the gameObject remains on screen, while I need it to be destroyed as well.

I know I could add a function to myClass in order to destroy the gameObject, and call it just before setting the class to null, but I’d really prefer calling it directly from the destructor for simplicity’s sake.
So my question is :
What’s the simplest solution to destroy a gameObject of a class when destroying the class itself ?

In 99% of all cases you don’t want to use a destructor (finalizer) at all:

The destructor is called by the garbage collector which runs on a different thread. Custom managed classes never ever use a destructor unless you have unmanaged resources which need to be cleaned up. Never rely on a destructor to do something which should be in a manually called method. The destructor / finalizer in C# has nothing to do with a destructor in C++.

I was trying some method without success. I think, it’s impossible. See forum links. Maybe, with destroy class, you destroy and GameObject, which class is attach. Then use function OnDestroy().

Well I read the links, and as I said, implementing an IDisposable interface doesn’t get Dispose() call when setting to null. When calling Dispose(), the instructions in Dispose() are called, but the class isn’t set to null, and thus, if I’m trying to get rid of the class instance in a array of class instances, the instance remains, unless I call Dispose then set it to null.
So as I mentionned, I have to call Dispose and then set the class to null, which I wanted to avoid. It is a shame that it is not possible,
Also, I have a computer science book about programming in C# with Unity, and the author does use constructors and destructors.
Anyways, thanks for the replies ( and the downvote :wink: ), think I’ll just create my own method to get rid of the GameObject instance