Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a .Net/C# object call Dispose() on itself?

Below is some sample code written by a colleague. This seems obviously wrong to me but I wanted to check. Should an object call its own Dispose() method from within one of its own methods? It seems to me that only the owner/creator of the object should call Dispose() when it's done with the object and not the object itself.

It's an .asmx web method that calls Dispose() on itself when it's done. (The fact that it's a web method is probably incidental to the question in general.) In our code base we sometimes instantiate web service classes within methods of other web services and then call methods on them. If my code does that to call this method, the object is toast when the method returns and I can't really use the object any more.

[WebMethod] public string MyWebMethod() {     try     {         return doSomething();     }     catch(Exception exception)     {         return string.Empty;     }     finally     {         Dispose(true);     } } 

UPDATE: Found a few links that are related:

Do I need to dispose a web service reference in ASP.NET?

Dispose a Web Service Proxy class?

like image 240
Tom Winter Avatar asked Feb 18 '11 18:02

Tom Winter


People also ask

Can you use .NET with C?

. NET Framework is an object oriented programming framework meant to be used with languages that it provides bindings for. Since C is not an object oriented language it wouldn't make sense to use it with the framework.

Is .NET still used in 2022?

A survey released by Stack Overflow this year in 2022 categorized the . NET Framework and . NET Core into one. It had increased in popularity from 34.2 percent to 34.55 percent to become the most popular frameworks list this year.

Is it worth learning .NET 2022?

Yes, It is worth learning C# in 2022 because it is the primary programming language which helps in every higher level programming languages. Not only C# can be used to build Windows applications but we can build applications that target Linux, MacOS, iOS, and Android operating systems.

Is .NET a good career in 2022?

. NET, being one of the favorite frameworks for developers, offers several opportunities. With its usage in enterprise-level development, a job in a high-tech company is highly likely.


1 Answers

For sure it's not a good prartice. The caller should decide when he is finished using the IDisposable object, not an object itself.

like image 89
EvgK Avatar answered Sep 23 '22 11:09

EvgK