473,406 Members | 2,698 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,406 software developers and data experts.

Why does this work?

Hi All,

I am new to VB.NET, and am confused by following code. The code
basically obtains an instance of an object from a helper method. This
helper method instantiates a new object, and returns it. But in its
Finally block, it sets the returned object to Nothing. What perplexes
me is that caller receives a valid object instance.

The queston is: does this work because I am lucky, or this is really
an expected behavior? Also, is this a correct coding practice? Will
appreciate explanation.

Thanks!

Gagan
=============

Module Module1

Class Salary
Private m_Amount As Double = 0.0

Public Property Amount() As Double
Get
Return m_Amount
End Get
Set(ByVal value As Double)
m_Amount = value
End Set
End Property
End Class

Public Function GetSalary(ByVal dblAmount As Double) As Salary

Dim pSalary As Salary = Nothing

Try
pSalary = New Salary()
pSalary.Amount = dblAmount

Return pSalary
Catch ex As Exception
'
Finally
pSalary = Nothing
End Try

End Function
Sub Main()
Dim pSalary As Salary = GetSalary(100.0)
System.Console.WriteLine(pSalary.Amount)
End Sub

End Module

Aug 5 '07 #1
12 1330
"Gagan" <Ga***************@gmail.comschrieb
Hi All,

I am new to VB.NET, and am confused by following code. The code
basically obtains an instance of an object from a helper method.
This helper method instantiates a new object, and returns it. But in
its Finally block, it sets the returned object to Nothing. What
perplexes me is that caller receives a valid object instance.

The queston is: does this work because I am lucky, or this is really
an expected behavior?
This is expected. You set the value of the local variable pSalary in the
Finally block, but when the Return statement has been executed (before), the
variable was not nothing, thus the function return value is not Nothing.
What you do to the local variable after setting the return value has no
effect on the return value.
Also, is this a correct coding practice?
Which practice? If you mean setting local variables to Nothing before the
end of the procedure, only very few people do this. I don't because it's
superfluous because the variable is running out of scope anyways.

Armin

Will
appreciate explanation.

Thanks!

Gagan
=============

Module Module1

Class Salary
Private m_Amount As Double = 0.0

Public Property Amount() As Double
Get
Return m_Amount
End Get
Set(ByVal value As Double)
m_Amount = value
End Set
End Property
End Class

Public Function GetSalary(ByVal dblAmount As Double) As Salary

Dim pSalary As Salary = Nothing

Try
pSalary = New Salary()
pSalary.Amount = dblAmount

Return pSalary
Catch ex As Exception
'
Finally
pSalary = Nothing
End Try

End Function
Sub Main()
Dim pSalary As Salary = GetSalary(100.0)
System.Console.WriteLine(pSalary.Amount)
End Sub

End Module
Aug 5 '07 #2
On Aug 5, 2:53 am, "Armin Zingler" <az.nos...@freenet.dewrote:
>
This is expected. You set the value of the local variable pSalary in the
Finally block, but when the Return statement has been executed (before), the
variable was not nothing, thus the function return value is not Nothing.
What you do to the local variable after setting the return value has no
effect on the return value.
Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.

I have another question: what exactly happens when the return
statement is executed? It apparently doesn't return the control to
the caller immediately. Probably it pushes the return value on the
stack, so that caller can pop it - and later changes to the local
variable doesn't affect the value on the stack. Is this correct
thinking?

Thanks for the response.

Gagan
Aug 6 '07 #3
Gagan,
Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.
This is absolute not what Armin wrote. Just read his message again.

Cor

Aug 6 '07 #4
On Aug 5, 9:40 pm, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
Gagan,
Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.

This is absolute not what Armin wrote. Just read his message again.

Cor
I read his message again. Can you tell me where the object is created
as a result of calling the New() ?

Thanks.

Gagan

Aug 6 '07 #5
At the start of the Try Block

Try
pSalary = New Salary()
pSalary.Amount = dblAmount

Return pSalary

--
Dave Griffiths
Gagan wrote:
On Aug 5, 9:40 pm, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
Gagan,
Ok, I understand. The variable is local, but it points to the
object that is allocated on the heap.
This is absolute not what Armin wrote. Just read his message again.

Cor

I read his message again. Can you tell me where the object is created
as a result of calling the New() ?

Thanks.

Gagan
Aug 6 '07 #6
"Gagan" <Ga***************@gmail.comschrieb
On Aug 5, 2:53 am, "Armin Zingler" <az.nos...@freenet.dewrote:

This is expected. You set the value of the local variable pSalary
in the Finally block, but when the Return statement has been
executed (before), the variable was not nothing, thus the function
return value is not Nothing. What you do to the local variable
after setting the return value has no effect on the return value.

Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.
You probably assume that the return value is a reference to the local
variable, but it is not. If that was the case, you were right.

What happens is, the Return statement sets the function return value. The
return value is a reference to an object. The caller gets a copy of the
reference to the object. In general, after modifying the source of a copy,
the copy remains unchanged. In your case, the local variable holding the
reference to the object is copied. Changing the local variable doesn't
affect the copy, i.e. the function return value, made before.
I have another question: what exactly happens when the return
statement is executed? It apparently doesn't return the control to
the caller immediately. Probably it pushes the return value on the
stack, so that caller can pop it - and later changes to the local
variable doesn't affect the value on the stack. Is this correct
thinking?
The return statement
1. sets the function return value
2. processes the finally sections of enclosing try-sections (this includes
using sections)
3. exits the function.

The function return value is not returned on the stack. Internally, 32-Bit
values are usually returned in a processor registers (EAX). This includes
object references (at least on a 32-Bit target plattform) that are also
32-Bit values. But that's implementation detail, so it may change in future
runtime/JIT versions. Calling conventions:
http://en.wikipedia.org/wiki/Calling_convention
http://en.wikipedia.org/wiki/X86_calling_conventions
Armin

Aug 6 '07 #7
Gagan wrote:
On Aug 5, 9:40 pm, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
>Gagan,
>>Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.
This is absolute not what Armin wrote. Just read his message again.

Cor

I read his message again. Can you tell me where the object is created
as a result of calling the New() ?

Thanks.

Gagan
On the heap. Just as you said. :)

You were absolutely correct in your analysis.

The variable is local, and it's a reference to the object that is
created on the heap. When you copy the reference into the return value,
there are two references to the same object. Changing the reference in
the local variable after the return value has been set doesn't affect
the return value and doesn't affect the object on the heap.

--
Göran Andersson
_____
http://www.guffa.com
Aug 6 '07 #8
Hi Gagan,

Let me try to explain form a different approach.

First in the Finally block change the pSalary = Nothing to something like
pSalary.Amount = 20
You'll see the output is 20. So the pSalary variable is pointing at the
Salary object that is returned.

Now change the code back to how you had it, setting pSalary to Nothing.
What that does is means the pSalary varaible is no longer pointing to the
object in the heap. That Object however has been assigned to functions
return value already though so changes to the pSalary variable make no
changes to what is returned, but changes to the Object itself do.

So the behaviorual equivalent of the code is :
Public Function GetSalary(ByVal dblAmount As Double) As Salary

Dim hidden_return_value_on_stack As Salary
Dim pSalary As Salary = Nothing

Try
pSalary = New Salary()
pSalary.Amount = dblAmount

hidden_return_value_on_stack = pSalary
Catch ex As Exception
'
Finally
pSalary = Nothing
End Try

' automatically returns hidden_return_value_on_stack
End Function


In VB you can actually write this using the method name, but I prefer not to
as the code can be more confusing especially is there are any overloads, eg:

Public Function GetSalary(ByVal dblAmount As Double) As Salary

Dim pSalary As Salary = Nothing

Try
pSalary = New Salary()
pSalary.Amount = dblAmount

GetSalary = pSalary
Catch ex As Exception
'
Finally
pSalary = Nothing
End Try

' automatically returns GetSalary
End Function

"Gagan" <Ga***************@gmail.comwrote in message
news:11**********************@g12g2000prg.googlegr oups.com...
Hi All,

I am new to VB.NET, and am confused by following code. The code
basically obtains an instance of an object from a helper method. This
helper method instantiates a new object, and returns it. But in its
Finally block, it sets the returned object to Nothing. What perplexes
me is that caller receives a valid object instance.

The queston is: does this work because I am lucky, or this is really
an expected behavior? Also, is this a correct coding practice? Will
appreciate explanation.

Thanks!

Gagan
=============

Module Module1

Class Salary
Private m_Amount As Double = 0.0

Public Property Amount() As Double
Get
Return m_Amount
End Get
Set(ByVal value As Double)
m_Amount = value
End Set
End Property
End Class

Public Function GetSalary(ByVal dblAmount As Double) As Salary

Dim pSalary As Salary = Nothing

Try
pSalary = New Salary()
pSalary.Amount = dblAmount

Return pSalary
Catch ex As Exception
'
Finally
pSalary = Nothing
End Try

End Function
Sub Main()
Dim pSalary As Salary = GetSalary(100.0)
System.Console.WriteLine(pSalary.Amount)
End Sub

End Module
Aug 6 '07 #9
On Aug 6, 7:42 am, "Bill McCarthy" <B...@NOSPAM.comwrote:
Hi Gagan,

Let me try to explain form a different approach.

First in the Finally block change the pSalary = Nothing to something like
pSalary.Amount = 20
You'll see the output is 20. So the pSalary variable is pointing at the
Salary object that is returned.
Bill,

That's exactly what I had done to figure out that object was created
on heap and pSalary was just a pointer to it :) Thanks!

Gagan

Aug 6 '07 #10
On Aug 5, 11:59 pm, "Armin Zingler" <az.nos...@freenet.dewrote:
"Gagan" <Gagan.Gajabaha...@gmail.comschrieb
On Aug 5, 2:53 am, "Armin Zingler" <az.nos...@freenet.dewrote:
This is expected. You set the value of the local variable pSalary
in the Finally block, but when the Return statement has been
executed (before), the variable was not nothing, thus the function
return value is not Nothing. What you do to the local variable
after setting the return value has no effect on the return value.
Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.
<Snip>

Thanks, Armin, for the explanation.

Gagan

Aug 6 '07 #11
On Aug 5, 11:59 pm, "Armin Zingler" <az.nos...@freenet.dewrote:
"Gagan" <Gagan.Gajabaha...@gmail.comschrieb
On Aug 5, 2:53 am, "Armin Zingler" <az.nos...@freenet.dewrote:
This is expected. You set the value of the local variable pSalary
in the Finally block, but when the Return statement has been
executed (before), the variable was not nothing, thus the function
return value is not Nothing. What you do to the local variable
after setting the return value has no effect on the return value.
Ok, I understand. The variable is local, but it points to the object
that is allocated on the heap.

You probably assume that the return value is a reference to the local
variable, but it is not. If that was the case, you were right.
<snip>

Armin,

I found that my real reason for the confusion was my assumption that
return statement must be returning control back to the caller. And, in
my infinite wisdom, I also thought that compiler must be smart enough
to generate the code such that it would execute the finally block
before the return is executed. But that is not so, as I learnt.
Thanks!

Gagan

Aug 6 '07 #12
On Aug 5, 12:51 am, Gagan <Gagan.Gajabaha...@gmail.comwrote:
Hi All,

I am new to VB.NET, and am confused by following code. The code
basically obtains an instance of an object from a helper method. This
helper method instantiates a new object, and returns it. But in its
Finally block, it sets the returned object to Nothing. What perplexes
me is that caller receives a valid object instance.

The queston is: does this work because I am lucky, or this is really
an expected behavior? Also, is this a correct coding practice? Will
appreciate explanation.
Many thanks to everyone for their responses, I really learnt something
out of this.

Gagan
Aug 6 '07 #13

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

Similar topics

7
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As...
3
by: Julian | last post by:
Hi I am trying to update a date field in my table but some how this simple code does not work, I know the select work because if I write the fields, it will show the data from the table but why...
5
by: me | last post by:
I have a Class Library that contains a Form and several helper classes. A thread gets created that performs processing of data behind the scenes and the Form never gets displayed (it is for debug...
22
by: Robert Bralic | last post by:
CAN anybody tell me any address where I can download some small(1000-2000) lines C++ proghram source. Or send me ,a small(1000-2000) lines C++ program source that I can compille with gpp under...
12
by: Frank Hauptlorenz | last post by:
Hello Out there! I have a DB2 V7.2 Database (Fix11) on Win 2000 Professional. It was before a NT 4 based Domain - now it is a Win 2000 Domain. The database server is a domain member. Now...
0
by: Jarod_24 | last post by:
How does tabindex work in ASP .net pages I dosen't seem to work quite like in regular forms. and there isn't any TabStop property either. 1 .How do you prevent a control form beign "tabbed"....
14
by: Anoop | last post by:
Hi, I am new to this newsgroup and need help in the following questions. 1. I am workin' on a GUI application. Does C# provides Layout Managers the way Java does to design GUI? I know that it...
89
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be...
14
by: webEater | last post by:
I have a problem, it's not browser specific, and I don't get a solution. I have an (X)HTML document, I show you a part of it: .... <!--<div class="pad">--> <div id="eventImages"><img src=""...
1
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
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...
0
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,...
0
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...

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.