Groups | Blog | Home
all groups > c# > september 2007 >

c# : What's the difference, if any?


Carl Johansson
9/1/2007 6:41:35 PM
Except for the syntax, what is the difference, if any, between this...

/* ---------------------------------------------------------------------- */
private void Form1_Paint(object sender, PaintEventArgs e)
{
Pen pen = null;

try
{
pen = new Pen(Color.MidnightBlue, 1.0F);
e.Graphics.DrawLine(pen, new Point(20, 270), new Point(20, 10));
}
finally
{
if (pen != null)
pen.Dispose();
}
}
/* ---------------------------------------------------------------------- */

and this...

/* ---------------------------------------------------------------------- */
private void Form1_Paint(object sender, PaintEventArgs e)
{
using (Pen pen = new Pen(Color.MidnightBlue, 1.0F))
e.Graphics.DrawLine(pen, new Point(20, 270), new Point(20, 10));
}
/* ---------------------------------------------------------------------- */

?

Regards Carl Johansson




Morten Wennevik [C# MVP]
9/1/2007 7:04:12 PM
On Sat, 01 Sep 2007 18:41:35 +0200, Carl Johansson <carl.johansson@nogar=
[quoted text, click to view]

Hi Carl,

They are equal. The using stament is equal to try/finally and will call=
Dispose when the scope ends.


-- =

Happy coding!
Göran_Andersson
9/1/2007 7:24:00 PM
[quoted text, click to view]

This code:

Pen pen = null;
try {
pen = new Pen(Color.MidnightBlue, 1.0F);
e.Graphics.DrawLine(pen, new Point(20, 270), new Point(20, 10));
} finally {
if (pen != null) {
pen.Dispose();
}
}

is the exact equivalent of:

using (Pen pen = null) {
pen = new Pen(Color.MidnightBlue, 1.0F);
e.Graphics.DrawLine(pen, new Point(20, 270), new Point(20, 10));
}


This code:

using (Pen pen = new Pen(Color.MidnightBlue, 1.0F)) {
e.Graphics.DrawLine(pen, new Point(20, 270), new Point(20, 10));
}

is the exact equivalent of:

Pen pen = new Pen(Color.MidnightBlue, 1.0F);
try {
e.Graphics.DrawLine(pen, new Point(20, 270), new Point(20, 10));
} finally {
if (pen != null) {
pen.Dispose();
}
}

--
Göran Andersson
_____
AddThis Social Bookmark Button