473,765 Members | 2,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Understanding passing, using and destroying objects

Hi,
I'm new to .NET and am using VB .NET as I am from a VB background.

I am having difficulty understanding the way .NET handles, passes and uses
objects.
I have had a look at the Micrsoft Data Access Application blocks for .NET
and am struggling to understand the following:

1. When creating a function that returns a datareader, there is a datareader
instantiated inside the function. This datareader is then returned to the
calling function. What happens then to the datareader inside the function,
is this merely a pointer that the caller then uses or is the entire object
copied into a new datareader variable? Then, what happens to the datareader
inside the object, does it get destroyed??

In the example below I see 2 DataReader objects, one is called
'ExecuteReader' the other 'drReader, is drReader a pointer that then gets
assigned to 'ExecuteReader' and then passed back to the calling function???

Public Overloads Shared Function ExecuteReader(B yVal connectionStrin g As
String, _
ByVal commandType As
CommandType, _
ByVal commandText As
String) As SqlDataReader
' Pass through the call providing null for the set of SqlParameters
Dim drReader as SQLDataReader
drReader = ExecuteReader(c onnectionString , commandType, commandText,
CType(Nothing, SqlParameter()) )
Return drReader
End Function ' ExecuteReader
2. I have a function as listed below, it takes a datareader as an input and
processes this reader then returns an array. What I would like to know is
what happens to the datareader inside the function, must I destroy it, and
how does it get instantiated???

'
' This function takes a data reader, extracts the field details and
' places the data inside an array. It then returns the array.
'
Function TranslateData(B yVal drReader As SqlDataReader) As String(,)
'
' First dimension will hold the field names,
' second dimension will hold the value
'
Dim sRetVal(drReade r.FieldCount - 1, 1) As String
Dim schemaTable As DataTable = drReader.GetSch emaTable()
Dim myRow As DataRow
Dim myCol As DataColumn
Dim iRow As Integer = 0
'
' Traverse the fields in the reader
'
For Each myRow In schemaTable.Row s
'
' Retrieve the appropriate column
'
myCol = schemaTable.Col umns(1)
'
' Insert the column name into the array
'
sRetVal(iRow, 0) = myRow(myCol).To String
'
' Insert the actual value into the array
'
sRetVal(iRow, 1) = drReader.Item(i Row).ToString
iRow += 1
Next
Return sRetVal
End Function

Nov 21 '05 #1
3 1999
1. When the function creates its DataReader object, it allocates a block of
memory for the object and puts a pointer to that memory into the variable
(drReader). When the function returns this object to the calling procedure,
it is actually just returning the pointer to the object. No second object is
created, just a second pointer to the original object.

Within the function itself, the "drReader" variable will go out of scope,
and will (eventually) be destroyed by the garbage collector. But it's just
the pointer that is being destroyed, not the object itself. Because there is
another reference to the object (the one received by the calling procedure
once your function completes), the object itself will not be destroyed. Once
the other reference to the object is set to Nothing or goes out of scope, it
is then possible for the object itself to be terminated and garbage
collected.

2. In this case, the DataReader must have been instantiated by the calling
function, otherwise it wouldn't have anything to pass into the drReader
parameter. Within the function, this parameter again is just a reference to
the existing object. It will use that object, and when the function returns
the reference will go out-of-scope (and later be garbage collected). As
before, the object itself is probably still referenced by the calling
procedure, so it will not be destroyed until that reference is released.

You do not need to destroy the object within the function, but you could set
the reference to Nothing if you wanted. This would not destroy the object
due to the calling procedure still having a reference to it, it would just
clear your local reference.

You shouldn't try to destroy or terminate the object by calling methods such
as Close(), either. You could do this (and in some circumstances it would be
correct to), but to do so would probably cause problems as the code calling
into your procedure would most likely not expect this to happen, and would
fail when it continued trying to use the object.

The thing to remember with object references is that they are just
references -- they're just a pointer to the object in memory, not the
physical object itself. When you pass or return a reference, that's all
you're passing, the pointer to the object. If you want to experiment with
this, take a look at the "Is" keyword. This will compare two object
references and tell you whether they point to the same object.

--

(O)enone
Nov 21 '05 #2
Miquel,

An object exist as long as there is a reference too that object. See my
comments beneath your objects.

Public Overloads Shared Function ExecuteReader(B yVal connectionStrin g
As
String, _
ByVal commandType As
CommandType, _
ByVal commandText As
String) As SqlDataReader
' Pass through the call providing null for the set of SqlParameters
Dim drReader as SQLDataReader
drReader = ExecuteReader(c onnectionString , commandType,
commandText,
CType(Nothing, SqlParameter()) )
Return drReader
End Function ' ExecuteReader
You are returning here a new created drReader, so it will normally exist
(when you have not set the resulting reader global) until the end of the
method that calls this method exist (it exist something longer until it is
destroyed by the garbage collector, however you cannot use it anymore).
Because it is a shared Function everything will however exist for the
complete time of the program.

The way you do it is probably bad practise because you leave as I assume
your connection open all the time. See for that the text in your second
sample.

2. I have a function as listed below, it takes a datareader as an input
and
processes this reader then returns an array. What I would like to know is
what happens to the datareader inside the function, must I destroy it, and
how does it get instantiated???

'
' This function takes a data reader, extracts the field details and
' places the data inside an array. It then returns the array.
'
Function TranslateData(B yVal drReader As SqlDataReader) As String(,)
'
' First dimension will hold the field names,
' second dimension will hold the value
'
Dim sRetVal(drReade r.FieldCount - 1, 1) As String
Dim schemaTable As DataTable = drReader.GetSch emaTable()
Dim myRow As DataRow
Dim myCol As DataColumn
Dim iRow As Integer = 0
'
' Traverse the fields in the reader
'
For Each myRow In schemaTable.Row s
'
' Retrieve the appropriate column
'
myCol = schemaTable.Col umns(1)
'
' Insert the column name into the array
'
sRetVal(iRow, 0) = myRow(myCol).To String
'
' Insert the actual value into the array
'
sRetVal(iRow, 1) = drReader.Item(i Row).ToString
iRow += 1
Next
Return sRetVal
End Function

The datareader is not opened inside this function, it seems to be a global
datareader, so you should not close it as well in this function. Open and
close in the same method.

I personally would create the connection and the datareader and close the
datareader and dispose than the connection in this method. Than it will be
destroyed by the garbage collector because there is no reference anymore to
this.

I hope this gives some ideas

Cor
Nov 21 '05 #3
On Wed, 17 Nov 2004 11:07:46 +0200, Miguel wrote:
In the example below I see 2 DataReader objects, one is called
'ExecuteReader' the other 'drReader, is drReader a pointer that then gets


There is only one DataReader, drReader. ExecuteReader is not a DataReader
but a function call. It calls an overloaded version of the ExecuteReader
function.
--
Chris

dunawayc[AT]sbcglobal_lunch meat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
Nov 21 '05 #4

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

Similar topics

3
14947
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
5
1545
by: JustSomeGuy | last post by:
Silly question maybe... I pass a refrence to an object to a method... The method adds the object to a (stl) list of these objects... However if a refrence to the object is passed and then added list... if the original object is destroyed.. is the object in the list invalid or is a copy of the object made by the stl list for insertion purposes
9
4804
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
16
12312
by: Peter Ammon | last post by:
Often times, I'll have some malloc()'d data in a struct that need not change throughout the lifetime of the instance of the struct. Therefore, the field within the struct is declared a pointer to const . But then free() complains when I pass in the pointer because free() is declared as void free(void*). So I have to cast. Why is it not declared as void free(const void*), which would save me these headaches? -Peter
6
3255
by: Scott Zabolotzky | last post by:
I'm trying to pass a custom object back and forth between forms. This custom object is pulled into the app using an external reference to an assembly DLL that was given to me by a co-worker. A query-string flag is used to indicate to the page whether it should instantiate a new instance of the object or access an existing instance from the calling page. On the both pages I have a property of the page which is an instance of this custom...
2
1336
by: jaymtz78 | last post by:
Hi, I have a huge windows application that I'm working on and I'm completely baffled. Sometimes when I try to close the application, it won't let me! I have an Exit button in my menu bar that has Application.Exit and works all the time, but if I try to Alt + F4 or click the 'X' in the Control Box...it won't let me exit the application sometimes unless I test to see if the 'X' was clicked and the use Application.Exit there too. I...
4
2706
by: Olumide | last post by:
Hello - I have two classes A and B as follows: class B{ public: ~B(){ cout << "destroying B" << endl; } }; class A{
4
2813
by: Deckarep | last post by:
Hello fellow C# programmers, This question is more about general practice and convention so here goes: I got into a discussion with a co-worker who insisted that as a general practice all objects should be passed by reference using the ref keyword generally speaking because as the writer of code you are conveying your intentions that an Object should/can be modified by your function.
5
1791
by: Markus Pitha | last post by:
Hello, I have a class "Menu". In this class I declare an object "Controller". Now I have a problem: Controller uses a ctor but I get the value I have to pass later in my program. The only way to solve this is to make a new instance of "Controller" and use it dynamically, but how can I use it as static object? class Menu {
0
9568
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
9404
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
10007
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
9959
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
9835
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
6649
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();...
0
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.