473,500 Members | 1,898 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object pointer management in C# (from a C++ perspective)

Hi,

please consider the following scenario:

I allocate some objects in C# using new.
e.g.:

MyObject x = new MyObject();

then I assign this object to several places, e.g. in Tag field in
ListViewItem, in some collection like List<MyObject>, etc.
The point is that the same 'x' is assigned to several different places.

If I clear the listview control, can I be sure that the List<MyObject>
container still stores reference to 'x' object?

And if I clear the List<MyObjectcontainer, can I be sure that the listview
control ListViewItem.Tag field stores valid reference to 'x' object?

The point is that I have a C++ background, and in C++ I can explicitly
control pointers to objects (or use smart pointers wrappers like
shared_ptr<Ttemplate), instead C# abstracts all that from me.

I'd like know if I can trust the C# run-time in scenarios like one described
above, i.e. the garbage collector does not destroy objects that I'm using in
other contexts of the same application.

Or is there some kind of explicit reference counting mechanism that I should
use in C#, like COM IUnknown::AddRef and Release?
i.e. should I call something like x.AddRef() when I store 'x' somewhere, and
x.Release() when I do not need 'x' anymore in that particular place?

Last question:
Is it possible to have RAII in C#?
(This could be useful for classes that manage resources like a file...)
Is 'using' keyword the only option in C# for something similar to C++ RAII?

Thank you very much,
Giovanni

Nov 23 '07 #1
5 2189
On 2007-11-23 09:39:44 -0800, "Giovanni Dicanio"
<gi**************@invalid.itsaid:
[...]
MyObject x = new MyObject();

then I assign this object to several places, e.g. in Tag field in
ListViewItem, in some collection like List<MyObject>, etc.
The point is that the same 'x' is assigned to several different places.

If I clear the listview control, can I be sure that the List<MyObject>
container still stores reference to 'x' object?
Yes, of course.
And if I clear the List<MyObjectcontainer, can I be sure that the listview
control ListViewItem.Tag field stores valid reference to 'x' object?

The point is that I have a C++ background, and in C++ I can explicitly
control pointers to objects (or use smart pointers wrappers like
shared_ptr<Ttemplate), instead C# abstracts all that from me.
A reference type variable is pretty much the same as a pointer here.
In fact, I'm pretty sure it's stored as a pointer.
I'd like know if I can trust the C# run-time in scenarios like one described
above, i.e. the garbage collector does not destroy objects that I'm using in
other contexts of the same application.
The whole point of the garbage collector is to _only_ collect an object
when there are no longer any references to it. So of course, if you
have stored a reference to an object it won't be collected.

If anything, the opposite problem is more typical, with a programmer
forgetting that they have written code to store a reference somewhere,
and accidently causing object lifetimes to be extended beyond what they
should be.
Or is there some kind of explicit reference counting mechanism that I should
use in C#, like COM IUnknown::AddRef and Release?
i.e. should I call something like x.AddRef() when I store 'x' somewhere, and
x.Release() when I do not need 'x' anymore in that particular place?
No. The whole point of the C# memory model is to avoid that.
Last question:
Is it possible to have RAII in C#?
(This could be useful for classes that manage resources like a file...)
Is 'using' keyword the only option in C# for something similar to C++ RAII?
Basically, yes. And note that "using" is really no different from
writing your own try/finally block.

Of course, depending on your definition of "RAII" something as simple
as error-checking and using a "goto" statement _could_ be considered
"RAII". That's also supported in C#.

C# objects don't have destructors. Classes aren't ever stored on the
stack anyway, so only structs would provide something like this
internal to to the class, and they don't have anything that provides a
mechanism to execute some code as the struct goes out of scope.

So, sure...it's possible to have RAII-like behavior in C#, but
depending on your definition of "RAII" you may not be able to implement
it exactly as you're expecting to or would like to.

Pete

Nov 23 '07 #2
>If I clear the listview control, can I be sure that the List<MyObject>
>container still stores reference to 'x' object?
Yes

>And if I clear the List<MyObjectcontainer, can I be sure that the listview
control ListViewItem.Tag field stores valid reference to 'x' object?
Yes

>Last question:
Is it possible to have RAII in C#?
(This could be useful for classes that manage resources like a file...)
Is 'using' keyword the only option in C# for something similar to C++ RAII?
Yes, using is the way to go.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 23 '07 #3
Peter Duniho wrote:
On 2007-11-23 09:39:44 -0800, "Giovanni Dicanio"
<gi**************@invalid.itsaid:
>I'd like know if I can trust the C# run-time in scenarios like one
described
above, i.e. the garbage collector does not destroy objects that I'm
using in
other contexts of the same application.

The whole point of the garbage collector is to _only_ collect an object
when there are no longer any references to it. So of course, if you
have stored a reference to an object it won't be collected.
Objects can be GC'ed even though there are references to them.

Objects are GC'ed when they are not reachable.

This avoid memory leaks of the type where the only reference to A is
in B and the only reference to B is in A.

But to the original question: yes - it works. I have never heard
about a bug where objects got GC'ed that were not supposed to. That
does not preclude that such a bug has existed in the past or will
in the future. But it is extremely unlikely. About the same
chance that a C++ new will allocate the same memory twice due to
a bug in the implementation.

Arne
Nov 24 '07 #4

"Arne Vajhøj" <ar**@vajhoej.dkha scritto nel messaggio
news:47***********************@news.sunsite.dk...
But to the original question: yes - it works.
Thank you all for all your answers.
I have never heard
about a bug where objects got GC'ed that were not supposed to.
I'd like to clarify that I have not experienced any bug about that.
I was just asking to be sure about this aspect of C# memory management.

Giovanni

Nov 24 '07 #5
Giovanni... You can use using in C# or stack like semantics in C++/CLI.

http://www.geocities.com/jeff_louie/...estructors.htm

FWIW, if you like the C++ Standard Template Library, STL/CLI is included
in Visual Studio 2008 C++/CLI.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 25 '07 #6

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

Similar topics

0
2118
by: Scott Abel | last post by:
For immediate release: The Rockley Group Content Management Workshop Series Coming to Atlanta, Seattle, Vancouver, Chicago, Washington, DC, Toronto, and Research Triangle Park Learn more:...
31
3283
by: Jamie Burns | last post by:
Hello, I am writing a client / server application. There is 1 server, and many clients. The server processes requests from each client, and typically creates and manipulates C++ objects on their...
11
9208
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in...
29
1866
by: Tim Clacy | last post by:
Am I correct in think that you can't re-assign a reference to a different object? If so, what should happen here: struct A { DoSomeThing(); }; A& GetNextA();
6
7940
by: Squeamz | last post by:
Hello, Say I create a class ("Child") that inherits from another class ("Parent"). Parent's destructor is not virtual. Is there a way I can prevent Parent's destructor from being called when a...
11
1956
by: jacob navia | last post by:
I am writing software to make a general storage facility of any kind of objects to/from disk. The intermeidate format used is XML, using the schema (modified a bit) of Microsoft:...
12
1991
by: Belebele | last post by:
Suppose that a class A depends on class B because an object of class B is passed into A's constructor. See below: class B { ... }; class A { public: A(B const& b); ... };
7
2842
by: Arpan | last post by:
The .NET Framework 2.0 documentation states that An Object variable always holds a pointer to the data, never the data itself. Now w.r.t. the following ASP.NET code snippet, can someone please...
6
2230
by: Pablo | last post by:
Hello, I am writing a windows application using C++ and BorlandBuilder 6 compiler. It is an event driven program and I need to create objects of some classes written by me. One of the classes...
0
7018
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
7182
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7232
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...
1
6906
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...
1
4923
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...
0
4611
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...
0
3110
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...
0
3106
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
316
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...

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.