Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all.. :)
I wanna ask you about IDisposable. What if my class doesn't have constructor when we want to implement IDisposable interface ? Is there any problem ? May you explain me ?? :) Thanks
Posted

If you don't explicitly include a constructor C# will automatically provide a default constructor that takes no arguments. (See Using Constructors[^])

There is no problem implementing IDisposable on a class that contains only the default constructor.

It is also possible to explicitly define the default constructor and mark it as private (preventing instantiation from outside of the class itself). Even in this case it is still perfectly OK to implement the IDisposable interface, but you will have to be aware of where you are instantiating your class from and who is responsible for calling Dispose(). You may find you have to call it manually rather than using the usual 'using' statement.
 
Share this answer
 
Comments
Teamsar Muliadi 8-Dec-10 4:24am    
Mmm.. after i read the link (msdn) above, i have a question for you. How about destructor if we don't have constructor ?? Thanks :)
Simon P Stevens 8-Dec-10 4:46am    
I'm not quite sure what you mean by "don't have a constructor"? You always have a constructor. Even if you don't declare one you automatically get a parameterless default one. Yes, you can always declare your own destructor even if you don't declare a constructor.
I believe the following few links will show you the right path

http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^]

http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx[^]

Besides this if you want to know something more please let me know
 
Share this answer
 
Comments
Teamsar Muliadi 8-Dec-10 4:19am    
It means that if we want to implement IDisposable interface, the class(es) must have constructor, doesn't it ?
(after i read your links).
senguptaamlan 8-Dec-10 4:27am    
Its not mandatory....The interface only gives us a method signature Dispose, which if we use cleaverly can clean up resource intensive instances from your class....Say for example I've a class with a private constructor and used Singleton pattern to get the instance of it....then if we use the object of this class within the using block then the ovverriden Dispose will be called automatically...I believe you know the basic difference between using a destructor and implementing IDisposable (Explicit and Implicit resource clean up)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900