473,387 Members | 1,553 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

using (object) a Mystery for me!!!

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 UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}

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

Console.ReadLine();
}
}

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.UseLimitedResource();
}

testC.UseLimitedResource();

Console.ReadLine();
}
}

Object is already disposed, still you can use it, driving to CRASHing
your own applications????

I appriciate your help understanding it properly.

-Cnu

Sep 9 '08 #1
9 1244
On Tue, 09 Sep 2008 10:47:26 -0700, Duggi <Du***************@gmail.com>
wrote:
[...]
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.UseLimitedResource();
}

testC.UseLimitedResource();

Console.ReadLine();
}
}

Object is already disposed, still you can use it, driving to CRASHing
your own applications????
Yes. The rule is don't try to use an object after it's been disposed.
The only exception is when the object itself clearly documents that it's
safe to use after disposal (rare, but not unheard of).

The code you posted violates the rule. It's no different than violating
any number of other rules in your code that lead to bugs when broken (for
example, trying to dereference a reference type when the variable has been
set to null...also allowed, but certainly not valid to do).

There are several reasons why C# can't prohibit the code example above,
but the exception described above is an important one. Such classes do
exist, and if the compiler prohibited the code you posted, it would block
otherwise legitimate code from working.

Pete
Sep 9 '08 #2
On Sep 9, 1:47*pm, Duggi <DuggiSrinivasa...@gmail.comwrote:
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.

}
It's nt the same, in the first you are explicitely telling the
compiler to Dispose the instance. If the type you place in the using
does not implement IDisposable yuo get an error:
using (Assembly a = Assembly.GetExecutingAssembly()){
}
You will get an error.

When you declare yuor instance INSDE the block, it simply is marked as
being disposable (if nobody hold a reference to it of course) but the
compile WILL NOT GENERATE code to dispose the instance.
class Program
{
static void Main(string[] args)
* * * {
TestC testC = new TestC()
* * * * * * using (testC)
* * * * * * {
* * * * * * * * testC.UseLimitedResource();
* * * * * * }

testC.UseLimitedResource();

* * * * * * Console.ReadLine();
* * * *}

}

Object is already disposed, still you can use it, driving to CRASHing
your own applications????
Not really, the object is marked as being disposable, it's not until
the GC runs that the object is REALLY disposed. Do a search for
WeakReference .
Besides your code is clearly a bad code, the compiler cannot prevent
htat kind of code from being written.
Sep 9 '08 #3
Ignacio Machin ( .NET/ C# MVP ) <ig************@gmail.comwrote:
Object is already disposed, still you can use it, driving to CRASHing
your own applications????

Not really, the object is marked as being disposable, it's not until
the GC runs that the object is REALLY disposed. Do a search for
WeakReference .
Besides your code is clearly a bad code, the compiler cannot prevent
htat kind of code from being written.
No, it's not "marked as disposable" - it *is* disposed, which is very
different from being garbage collected or finalized.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 9 '08 #4
On Sep 9, 1:31*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Ignacio Machin ( .NET/ C# MVP ) <ignacio.mac...@gmail.comwrote:
>
No, it's not "marked as disposable" - it *is* disposed, which is very
different from being garbage collected or finalized.
Whoa! Two MVPs disagreeing! Dangerous! Step back I see a brawl
a'comin'! :-)

My newbie answer to the OP is that points 1 and 2 of the OP are sound,
since 'using' is the same as:
'using (X) { //} is equivalent to (pseudo-code):

try { //} finally { if (X.Dispose();}

So 'using' is safer, since you can try a null pointer and it will not
crash your program, it will just trigger the catch or finally block.

RL

Sep 9 '08 #5
Duggi wrote:
Object is already disposed, still you can use it, driving to CRASHing
your own applications????
The Dispose method is just a method like any other, there is nothing
magical about it that would make it impossible to use the object after
it's called.

Most objects are not very useful once you called Dispose, but that's
because of the code that was put in the Dispose method, not because of
the call in and of itself.

--
Göran Andersson
_____
http://www.guffa.com
Sep 9 '08 #6
On Sep 9, 1:31*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Ignacio Machin ( .NET/ C# MVP ) <ignacio.mac...@gmail.comwrote:
Object is already disposed, still you can use it, driving to CRASHing
your own applications????
Not really, the object is marked as being disposable, it's not until
the GC runs that the object is REALLY disposed. Do a search for
WeakReference .
Besides your code is clearly a bad code, the compiler cannot prevent
htat kind of code from being written.

No, it's not "marked as disposable" - it *is* disposed, which is very
different from being garbage collected or finalized.

--
Jon Skeet - <sk...@pobox.com>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
Agreed. I think objects that are marked for finalization are garbage
collected when garbage collector is ran, However dispose will be
called then and there itself.

-Cnu
Sep 10 '08 #7
Duggi <Du***************@gmail.comwrote:
On Sep 9, 1:31*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Ignacio Machin ( .NET/ C# MVP ) <ignacio.mac...@gmail.comwrote:
Object is already disposed, still you can use it, driving to CRASHing
your own applications????
Not really, the object is marked as being disposable, it's not until
the GC runs that the object is REALLY disposed. Do a search for
WeakReference .
Besides your code is clearly a bad code, the compiler cannot prevent
htat kind of code from being written.
No, it's not "marked as disposable" - it *is* disposed, which is very
different from being garbage collected or finalized.
Agreed. I think objects that are marked for finalization are garbage
collected when garbage collector is ran, However dispose will be
called then and there itself.
Only if the finalizer is written to call Dispose. Finalization doesn't
*automatically* call Dispose. As far as the runtime is concerned,
IDisposable is just another interface and Dispose is just another
method.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #8


"raylopez99" <ra********@yahoo.comwrote in message
news:e7**********************************@j22g2000 hsf.googlegroups.com...
.... >SNIP<
My newbie answer to the OP is that points 1 and 2 of the OP are sound,
since 'using' is the same as:
'using (X) { //} is equivalent to (pseudo-code):

try { //} finally { if (X.Dispose();}

So 'using' is safer, since you can try a null pointer and it will not
crash your program, it will just trigger the catch or finally block.

RL
Close, but no...your pseudo-code is a little off or lacking a little.

using (X) {
// some code here
}

is similar to (but not 100% positive unless we reflect the IL):

// # Compilation check here to ensure X implements IDisposable.
try {
// some code here
} finally {
if (X != null) {
X.Dispose();
}
}

From my tests (again, I have not looked at the IL for this), there are a few
differences to my example than yours (besides the simple compilation errors
from the pseudo-code):

1.) There is a compilation check to make sure X implements IDisposable.
2.) In the finally block, there the code checks to see if X is NOT null.

A third thing that is similar for both, but doesn't really show unless you
see it or *understand* it is that you can declare and create an instance of
X for use ONLY in the using block, while you can't do the same thing in the
try...finally block.

Example:

using (MyClass X = new MyClass()) {
// some code here.
}

while you can't do:
try {
MyClass X = new MyClass();
// some code here.
} finally {
if (X != null) {
X.Dispose();
}
}

Hope this helps a bit more :)

Mythran
Sep 11 '08 #9
On Thu, 11 Sep 2008 16:34:10 -0700, Mythran <My*****@community.nospam>
wrote:
[...]
1.) There is a compilation check to make sure X implements IDisposable.
2.) In the finally block, there the code checks to see if X is NOT null.

A third thing that is similar for both, but doesn't really show unless
you see it or *understand* it is that you can declare and create an
instance of X for use ONLY in the using block, while you can't do the
same thing in the try...finally block.
In addition to the three points you've made, it's also helpful to know
that when using the "using" statement, the target variable used in the
"using" statement is read-only. The compiler will emit an error if you
try to modify its value inside the "using" statement.

The C# specification has these details on the various specific
requirements of the implementation of "using".

Pete
Sep 12 '08 #10

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

Similar topics

28
by: Christopher Benson-Manica | last post by:
I have the following document, at http://ataru.gomen.org/file/test.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head>...
2
by: Henry | last post by:
Hi guys, I want to write some global functions which can be called from different asp.net page. In Visual Basic, there is a global module which allow me to do that. In Visual Basic .net, I...
1
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...
4
by: darrell | last post by:
I recently wrote a program in Access VBA that contains this snippet of code: For i = 1 to TotalBanks With Me("txtBank" & Chr(i + 64)) .BackColor = vbBlue .ForeColor = vbWhite End With Next i...
9
Denburt
by: Denburt | last post by:
If you are in the VBA section of a form and want to refer to a control on that form then the quickest most efficient way of achieving a connection to this control would be the most direct Me!NewData....
11
by: Dudely | last post by:
The following file, as far as I know, should work. However, I get a blank page. Using IE 7 "test2.html" is a simple file which has nothing more than "Goodbye World" in it. Am I doing...
0
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...
2
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...
12
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.