473,725 Members | 2,193 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using(object) ??

I used to wonder why MS implemented C# to accept the following code

using (Font f = new Font())
{
// some code here.
}

While the same can be achieved through

{
Font f = new Font()
// some code here.
}

Just making code as a block and create the object inside the block.
Why MS took pain to implement the semantics to understand in C# it as
in first block.

As per my understanding the above code does the following things
1. Creates a block where f is used
2. When code block completes execution, f is garbage collected.

I was wrong. There is one major significant difference between the two
code blocks.

Actually, what ever the object used in the using(object) statement,
has to implement IDisposable. I think by now you got the difference.
The beauty of the using(object) statement is that after the execution
of the using block object.Dispose( ) will be called by the framework,
releasing all the unmanaged resources.

See below code:

class TestC : IDisposable
{
public void UseLimitedResou rce()
{
Console.WriteLi ne("Using limited resource...");
}

void IDisposable.Dis pose()
{
// this class uses significant unmanaged resources and are relesed
here.
Console.WriteLi ne("Disposing limited resource.");
}
}
class Program
{
static void Main(string[] args)
{
using (TestC testC = new TestC())
{
testC.UseLimite dResource();
}

Console.ReadLin e();
}
}

However I ran into another BIG doubt that why C# allows the following
code

class Program
{
static void Main(string[] args)
{
TestC testC = new TestC()
using (testC)
{
testC.UseLimite dResource();
}

testC.UseLimite dResource();

Console.ReadLin e();
}
}

Object is already disposed, still you can use it, driving to CRASHing
your own applications??? ?
I appriciate your help to continue this...

-Cnu
Sep 10 '08 #1
12 1570
class TestC : IDisposable
{
private bool IsDisposed = false; //******

public void UseLimitedResou rce()
{
Console.WriteLi ne("Using limited resource...");
}

protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
throw new ObjectDisposedE xception();

Console.WriteLi ne("Disposing limited resource.");
IsDisposed = true;
GC.SuppressFina lize(this);
}

void IDisposable.Dis pose()
{
Dispose(true);
}

~TestC()
{
Dispose(false);
}

}
Sep 10 '08 #2
Peter Morris <mr*********@SP AMgmail.comwrot e:
class TestC : IDisposable
{
private bool IsDisposed = false; //******

public void UseLimitedResou rce()
{
Console.WriteLi ne("Using limited resource...");
}

protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
throw new ObjectDisposedE xception();

Console.WriteLi ne("Disposing limited resource.");
IsDisposed = true;
GC.SuppressFina lize(this);
}

void IDisposable.Dis pose()
{
Dispose(true);
}

~TestC()
{
Dispose(false);
}

}
One issue with this: Dispose() shouldn't throw an exception when called
multiple times. From MSDN:

<quote>
If an object's Dispose method is called more than once, the object must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedE xception when
resources are already disposed.
</quote>

Personally I usually just seal the class and implement IDisposable
"simply" (and without a finalizer). The above more general pattern is
rarely necessary unless you're in complicated situations, IMO.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #3
On Sep 10, 8:57*am, "Peter Morris" <mrpmorri...@SP AMgmail.comwrot e:
*class TestC : IDisposable
*{
* * private bool IsDisposed = false; //******

* * public void UseLimitedResou rce()
* * {
* * * * Console.WriteLi ne("Using limited resource...");
* * }

* * protected virtual void Dispose(bool disposing)
* * {
* * * * if (IsDisposed)
* * * * * * throw new ObjectDisposedE xception();

* * * * Console.WriteLi ne("Disposing limited resource.");
* * * * IsDisposed = true;
* * * * GC.SuppressFina lize(this);
* * }

* * void IDisposable.Dis pose()
* * {
* * * * Dispose(true);
* * }

* * ~TestC()
* * {
* * * * Dispose(false);
* * }

*}
thats gre8, implementing a dispose() pattern suggested by MS.

However if my lazy developers does not implement this, and simply went
ahead with the code in the question, there must be a check from
runtime atleast for throwing an exception that object is already
disposed.

-Cnu.

Sep 10 '08 #4
On Wed, 10 Sep 2008 08:43:52 -0700, Duggi <Du************ ***@gmail.com>
wrote:
I used to wonder why MS implemented C# to accept the following code [...]
How is this different from the previous thread you started, and which you
finished up by saying that you got the "zest" of it?
Sep 10 '08 #5
On Sep 10, 9:16*am, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Peter Morris <mrpmorri...@SP AMgmail.comwrot e:
*class TestC : IDisposable
*{
* * private bool IsDisposed = false; //******
* * public void UseLimitedResou rce()
* * {
* * * * Console.WriteLi ne("Using limited resource...");
* * }
* * protected virtual void Dispose(bool disposing)
* * {
* * * * if (IsDisposed)
* * * * * * throw new ObjectDisposedE xception();
* * * * Console.WriteLi ne("Disposing limited resource.");
* * * * IsDisposed = true;
* * * * GC.SuppressFina lize(this);
* * }
* * void IDisposable.Dis pose()
* * {
* * * * Dispose(true);
* * }
* * ~TestC()
* * {
* * * * Dispose(false);
* * }
*}

One issue with this: Dispose() shouldn't throw an exception when called
multiple times. From MSDN:

<quote>
If an object's Dispose method is called more than once, the object must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedE xception when
resources are already disposed.
</quote>

Personally I usually just seal the class and implement IDisposable
"simply" (and without a finalizer). The above more general pattern is
rarely necessary unless you're in complicated situations, IMO.

--
Jon Skeet - <sk...@pobox.co m>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
Hi Jon,

<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedE xception when
resources are already disposed.
</quote>

Is this by implementing dispose pattern, or by default runtime can do
it?

When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.

-Cnu

Sep 10 '08 #6
On Sep 10, 9:42*am, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Wed, 10 Sep 2008 08:43:52 -0700, Duggi <DuggiSrinivasa ...@gmail.com*
wrote:
I used to wonder why MS implemented C# to accept the following code [....]

How is this different from the previous thread you started, and which you*
finished up by saying that you got the "zest" of it?
Apologies to all in this thread!!!

Yesterday night I tried asking a question with the title " using
(object) a Mystery for me!!! "

And the groups site displayed an error while posting it... however it
got posted correctly... here is the link
http://groups.google.com/group/micro...5000037a06e7b9

that why I stated a new thread / question.
The other question I had was about the XmlSerializatio n class... which
I got clarified with you. I am thankful to you for your valuable
replies. They helped me in understanding the XML Serialization class
more properly.

here is the link..
http://groups.google.com/group/micro...ed5934c71ba19e

The current question is about using(object)

-Cnu

Sep 10 '08 #7
Duggi <Du************ ***@gmail.comwr ote:
<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedE xception when
resources are already disposed.
</quote>

Is this by implementing dispose pattern, or by default runtime can do
it?
That's when you implement IDisposable.
When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.
How often do you implement IDisposable yourself? How often do you write
a using statement which *doesn't* declare a variable and create a new
instance of whatever you're using?

A modicum of care is required, but that's all.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #8
On Sep 10, 9:54*am, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Duggi <DuggiSrinivasa ...@gmail.comwr ote:
<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedE xception when
resources are already disposed.
</quote>
Is this by implementing dispose pattern, or by default runtime can do
it?

That's when you implement IDisposable.
When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.

How often do you implement IDisposable yourself? How often do you write
a using statement which *doesn't* declare a variable and create a new
instance of whatever you're using?

A modicum of care is required, but that's all.

--
Jon Skeet - <sk...@pobox.co m>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
Thanks Jon,

I understand that Dispose pattern is the solution for the bad code in
question. I really understand the importance of the dispose pattern
now.

Thanks to all of you in the discussion for your valuable time.

-Cnu

PS: I am trying to get myself more and more familier with .Net and C#.
If at all I ask any dumb dumb questions, please understand my level of
expertise.

Sep 10 '08 #9
Duggi wrote:
<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedE xception when
resources are already disposed.
</quote>

Is this by implementing dispose pattern, or by default runtime can do
it?

When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.

-Cnu
According to the guidelines, you should be able to do this:

TestC test = new TestC();
test.Dispose();
test.Dispose();

If the second call to Dispose throws an exception (which the code from
Peter Morris does), it doesn't follow the guidelines.

--
Göran Andersson
_____
http://www.guffa.com
Sep 10 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
17209
by: Joe Kelsey | last post by:
When you use addEventListener (or addEvent in IE) to call an object method, does it call it with the correct this parameter? The ECMAScript reference has a lot to say about the caller using Function.prototype.call or Function.prototype.apply and passing the correct this pointer for the context, but how does addEventListener determine the correct this pointer. Or does it just punt and pass the global context, thus making it impossible to...
0
1017
by: Aleksey Dmitriyev | last post by:
I am using Session property for my own serializable objects. The code snippet is below: // C# ASP.NET code behind private void btnRun_Click(object sender, System.EventArgs e) { MyClass myObj = new MyClass("abc", 99); Session = myObj;
7
1499
by: William Apple | last post by:
Despite the fact this deals with webservices I believe it is a VB question. I am working on a test application that passes data to a webservice. The webservices takes a variable type that is defined below: Public Class Variable Inherits MarshalByRefObject '<remarks/> Public strVariableName As String
1
2900
by: Ram | last post by:
Hi All, I am using Object Data Source to bind data in the gridview. I have set the property AllowSorting=true. While running the application, I could sort the data only in ascending order. Is there any way to achieve two way sorting in gridview ie. both ascending and descending on successive clicks ?. Please give me a suggestion to solve this issue. Thanks in advance.
6
1883
by: burningodzilla | last post by:
Hi all - I'm preparing to dive in to more complex application development using javascript, and among other things, I'm having a hard time wrapping my head around an issues regarding "inheritance" using the prototype property. I realize there are no classes in JS, that code therefore lives in objects instead of class definitions, and that "inheritance" must be achieved prototypically and not classically. That said, on with the code. Say I...
0
1390
by: sajithamol | last post by:
I have a dll of a VB application which performs image manipulations. I want to build this dll file into a .cab file to embed this in the Object tag in client side. Also how to generate the classid for the .cab file which is a required parameter for using Object tag.
2
1851
by: Veloz | last post by:
Hiya My question is whether or not you should associated related objects in your software using a scheme of id's and lookups, or wether objects should actually hold actual object references to objects they are associated with. For example, lets say you are modelling studen ratings of teachers. Let's say your applications needs to analyze these ratings for teachers and is provided a data file. In this data file the teachers all have...
0
1489
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi I have a gridview that binds to an object datasource. I added an update method to the object data source through the wizard. The update method takes an object as input and returns an object of the same type. Anyhow it looks like the code is trying to run the update method when the user selects the update button (command field button on the grid). It does not work since the object is not passed in. I am guessing I would need to...
9
1262
by: Duggi | last post by:
I used to wonder why MS implemented C# to accept the following code using (Font f = new Font()) { // some code here. } While the same can be achieved through {
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.