user2907335
user2907335

Reputation: 1

IDisposable in C#

I code following:

class myclass : IDisposable
{
    public int a;

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}
class Program
{
    static void Main(string[] args)
    {
        myclass cl = null;
        using (myclass n = new myclass())
        {

            n.a = 10;
            cl = n;
        }

        int a = cl.a;// statement 1
    }
}

I expect that statement 1 won't work because cl object have been released (n object have released). But It work. So Have n object really been released at statement 1 ?

Upvotes: 0

Views: 236

Answers (3)

supercat
supercat

Reputation: 81267

The garbage collector in .NET ensures that objects will continue to exist as long as any sort of reference exists to them (this is true even of things like weak references; if the only references to an object are weak references, the system will invalidate them; at that point, there won't be any references the object and it will cease to exist).

The purpose of Dispose is to change a possibly-usable object which might have outside entities doing things on its behalf to the possible detriment of other entities (e.g. granting it exclusive access to a file, making that file inaccessible to anyone else) to an object which no longer has any outside entities doing anything on its behalf, by notifying all such entities that their "services" are no longer required. An object which needs the services of outside entities will often become unusable if those entities stop performing those services, but the fact that disposed objects become unusable is not the purpose of Dispose, but merely a common consequence.

Upvotes: 1

Reacher Gilt
Reacher Gilt

Reputation: 1813

your attribute a is a managed resource. IDisposable is an interface for dealing with unmanaged code or resources.

Perhaps you are expecting the object to be destroyed? That's different than disposal.

Upvotes: 0

SLaks
SLaks

Reputation: 888047

There is no way to explicitly "release" a managed object.

Dispose() is a completely ordinary function which is intended to release unmanaged resources.
Calling it does not affect the GC at all.

Upvotes: 7

Related Questions