How much is Pointers different in C# compared to C++?
Do we have destructors in C#? if yes, for what do we use it?
--
Cheers,
Akhil 7 1754
Hi Akhil, How much is Pointers different in C# compared to C++?
Very different. Pointers do not exist in C#. Although you can still use pointers in "unsafe" code blocks.
Do we have destructors in C#? if yes, for what do we use it?
Basically no. You make sure there are no more references to an object and the garbage collector will release the memory shortly thereafter. You can still write a kind of destructor that will be called when the garbage collector is about to eat an object.
--
Happy coding!
Morten Wennevik [C# MVP]
There are a few things to be considered about pointers in C#:
(1) Any code using pointers cannot be 'managed' by CLR. So you've to put it
in 'unsafe' block.
(2) Any object in a program's memory can be garbage collected or moved to a
different location in memory without any notice by the garbage collector of
..NET runtime. To fix a pointer and memory pointed to by the pointer in
memory, you've to use 'fixed' clause. Any pointer declared inside a 'fixed'
expression will be pinned in memory and will not be moved by the GC.
(3) Any value types declared within an 'unsafe' block are automatically
treated as 'fixed' by the runtime and so these cannot appear within a 'fixed'
clause.
(4) As a guideline for use of pointers, you'll have to use them only when
execution speed is utmost important, or you've to call some Windows API
function which requires a pointer as a parameter.
About Destructors in C#:
(1) In general you don't need to worry about freeing memory. However when
your application encapsulates unmanaged resources such as windows, files, and
network connections, you should use destructors to free those resources.
(2) Destructor is called by the GC AFTER an object is marked for
destruction, that is when it is no longer refernced or it is no longer in
scope.
(3) The destructor implicitly calls the Object.Finalize () method.
(4) Destructors cannot be invoked explicitly. They cannot be inherited and
overloaded.
(5) Structs do not have destructors
(6) In general it's better to implement Dispose() method of IDisposable
interface and put the clean up code there, and call it whenever the object is
to be destroyed, because there is no guarantee when the destructor will be
called.
Hope this helps.
"Akhil" wrote: How much is Pointers different in C# compared to C++? Do we have destructors in C#? if yes, for what do we use it?
-- Cheers, Akhil
Thanks a lot Sameeksha...... that led to lot of clarity.
--
Cheers,
Akhil
"Sameeksha" <Sa*******@disc ussions.microso ft.com> wrote in message
news:1E******** *************** ***********@mic rosoft.com... There are a few things to be considered about pointers in C#: (1) Any code using pointers cannot be 'managed' by CLR. So you've to put
it in 'unsafe' block. (2) Any object in a program's memory can be garbage collected or moved to
a different location in memory without any notice by the garbage collector
of .NET runtime. To fix a pointer and memory pointed to by the pointer in memory, you've to use 'fixed' clause. Any pointer declared inside a
'fixed' expression will be pinned in memory and will not be moved by the GC. (3) Any value types declared within an 'unsafe' block are automatically treated as 'fixed' by the runtime and so these cannot appear within a
'fixed' clause. (4) As a guideline for use of pointers, you'll have to use them only when execution speed is utmost important, or you've to call some Windows API function which requires a pointer as a parameter.
About Destructors in C#: (1) In general you don't need to worry about freeing memory. However when your application encapsulates unmanaged resources such as windows, files,
and network connections, you should use destructors to free those resources. (2) Destructor is called by the GC AFTER an object is marked for destruction, that is when it is no longer refernced or it is no longer in scope. (3) The destructor implicitly calls the Object.Finalize () method. (4) Destructors cannot be invoked explicitly. They cannot be inherited and overloaded. (5) Structs do not have destructors (6) In general it's better to implement Dispose() method of IDisposable interface and put the clean up code there, and call it whenever the object
is to be destroyed, because there is no guarantee when the destructor will be called.
Hope this helps.
"Akhil" wrote:
How much is Pointers different in C# compared to C++? Do we have destructors in C#? if yes, for what do we use it?
-- Cheers, Akhil
there are a lot of misinformation in this post that needs to be corrected.
see inline
"Sameeksha" wrote: There are a few things to be considered about pointers in C#: (1) Any code using pointers cannot be 'managed' by CLR. So you've to put it in 'unsafe' block.
the wording of this seems somewhat misleading. to use pointers in a method
or a class, you need mark them unsafe, but it doesn't mean that CLR
completely ignores these blocks. in fact, the second point shows that they
are still very much affected by the CLR.
(2) Any object in a program's memory can be garbage collected or moved to a different location in memory without any notice by the garbage collector of .NET runtime. To fix a pointer and memory pointed to by the pointer in memory, you've to use 'fixed' clause. Any pointer declared inside a 'fixed' expression will be pinned in memory and will not be moved by the GC.
this only applies to managed heap.
(3) Any value types declared within an 'unsafe' block are automatically treated as 'fixed' by the runtime and so these cannot appear within a 'fixed' clause.
unsafe keyword doesn't intrinsically pin anything. the reason local
variables doesn't need to be fixed is because it's located on the stack, and
the stack is not subject to the GC.
(4) As a guideline for use of pointers, you'll have to use them only when execution speed is utmost important, or you've to call some Windows API function which requires a pointer as a parameter.
About Destructors in C#:
this is an area I feel that the doc is very misleading. there is no
destructor in .NET. C# uses the C destructor syntax to express
Object.Finalize (), but it's not really a destructor.
(1) In general you don't need to worry about freeing memory. However when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources. (2) Destructor is called by the GC AFTER an object is marked for destruction, that is when it is no longer refernced or it is no longer in scope. (3) The destructor implicitly calls the Object.Finalize () method. (4) Destructors cannot be invoked explicitly. They cannot be inherited and overloaded. (5) Structs do not have destructors (6) In general it's better to implement Dispose() method of IDisposable interface and put the clean up code there, and call it whenever the object is to be destroyed, because there is no guarantee when the destructor will be called.
actually, it's better to implement both. you should definitely implement
Dispose to free resource on demand. but you also need Finalize as a fail
safe in case Dispose wasn't called by the programmer. otherwise, you are
leaking resource.
the doc is being overly cautious when saying Finalizers are not guarantteed
to be called. in fact, Finalizers are guarantteed to be called as long as
your program doesn't terminate abnormally, meaning it didn't crash the
runtime, got into a deadlock or any other situation that forces you to kill
the process prematurely. In fact, I'd be very worried if it doesn't <em>at
least</em> guaranttee me that resources will be freed when I close my
application, that'd be a terrible platform.
Hope this helps.
"Akhil" wrote:
How much is Pointers different in C# compared to C++? Do we have destructors in C#? if yes, for what do we use it?
-- Cheers, Akhil
Daniel Jin is correct, there is a lot of misinformation. I'll try to clear up any that Daniel missed...
First of all, there are no destructors in C#. There are finalizers which are expressed using C++'s destructor syntax. After the Garbage Collector collects your dead reference
object (no more live references to it), if it implements a finalizer, it is put on the finalization queue and run at an undetermined time in the future by the GC's finalization thread. actually, it's better to implement both. you should definitely implement Dispose to free resource on demand. but you also need Finalize as a fail safe in case Dispose wasn't called by the programmer. otherwise, you are leaking resource.
Daniel is correct. Please see the Dispose pattern: http://msdn.microsoft.com/library/de...izedispose.asp
Note it's also a good idea to suppress the finalizer upon successful completion of Dispose, to avoid double freeing resources, and to avoid putting your object ont he
finalization queue, which is expensive, since it is promoted a generation, as are any objects it references.
the doc is being overly cautious when saying Finalizers are not guarantteed to be called. in fact, Finalizers are guarantteed to be called as long as your program doesn't terminate abnormally, meaning it didn't crash the runtime, got into a deadlock or any other situation that forces you to kill the process prematurely. In fact, I'd be very worried if it doesn't <em>at least</em> guaranttee me that resources will be freed when I close my application, that'd be a terrible platform.
Actually, there are other cases when a finalizer may not be run:
-When the appdomain that contains the object is "rudely" unloaded
-There is a finalizer that is starving the finalizers by hogging the finalizer thread (which has a timeout)
-The finalizer thread times out because of too many finalizable objects on the queue.
Don't worry thoug, when the CLR shuts down, unmanaged resources will be released, but buffers may not be flushed, and final writes may be lost.
Hope that helps!
-Chris
there are a lot of misinformation in this post that needs to be corrected. see inline
"Sameeksha" wrote:
There are a few things to be considered about pointers in C#: (1) Any code using pointers cannot be 'managed' by CLR. So you've to put it in 'unsafe' block.
the wording of this seems somewhat misleading. to use pointers in a method or a class, you need mark them unsafe, but it doesn't mean that CLR completely ignores these blocks. in fact, the second point shows that they are still very much affected by the CLR.
(2) Any object in a program's memory can be garbage collected or moved to a different location in memory without any notice by the garbage collector of .NET runtime. To fix a pointer and memory pointed to by the pointer in memory, you've to use 'fixed' clause. Any pointer declared inside a 'fixed' expression will be pinned in memory and will not be moved by the GC.
this only applies to managed heap.
(3) Any value types declared within an 'unsafe' block are automatically treated as 'fixed' by the runtime and so these cannot appear within a 'fixed' clause.
unsafe keyword doesn't intrinsically pin anything. the reason local variables doesn't need to be fixed is because it's located on the stack, and the stack is not subject to the GC.
(4) As a guideline for use of pointers, you'll have to use them only when execution speed is utmost important, or you've to call some Windows API function which requires a pointer as a parameter.
About Destructors in C#:
this is an area I feel that the doc is very misleading. there is no destructor in .NET. C# uses the C destructor syntax to express Object.Finaliz e(), but it's not really a destructor.
(1) In general you don't need to worry about freeing memory. However when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources. (2) Destructor is called by the GC AFTER an object is marked for destruction, that is when it is no longer refernced or it is no longer in scope. (3) The destructor implicitly calls the Object.Finalize () method. (4) Destructors cannot be invoked explicitly. They cannot be inherited and overloaded. (5) Structs do not have destructors (6) In general it's better to implement Dispose() method of IDisposable interface and put the clean up code there, and call it whenever the object is to be destroyed, because there is no guarantee when the destructor will be called.
actually, it's better to implement both. you should definitely implement Dispose to free resource on demand. but you also need Finalize as a fail safe in case Dispose wasn't called by the programmer. otherwise, you are leaking resource.
the doc is being overly cautious when saying Finalizers are not guarantteed to be called. in fact, Finalizers are guarantteed to be called as long as your program doesn't terminate abnormally, meaning it didn't crash the runtime, got into a deadlock or any other situation that forces you to kill the process prematurely. In fact, I'd be very worried if it doesn't <em>at least</em> guaranttee me that resources will be freed when I close my application, that'd be a terrible platform.
Hope this helps.
"Akhil" wrote:
> How much is Pointers different in C# compared to C++? > Do we have destructors in C#? if yes, for what do we use it? > > -- > Cheers, > Akhil > > >
--
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm
Note: For the benefit of the community-at-large, all responses to this message are best directed to the newsgroup/thread from which they originated.
> Actually, there are other cases when a finalizer may not be run: -When the appdomain that contains the object is "rudely" unloaded -There is a finalizer that is starving the finalizers by hogging the finalizer thread (which has a timeout) -The finalizer thread times out because of too many finalizable objects on the queue.
interesting. I wasn't aware of the last two points. I guess the doc was
right in the cautious approach. more reason not to rely on finalizers too
much. thanks for the information.
is there a reason why there's a timeout on the finalization thread? is it
to avoid a hanging finalizer, like one that is in a deadlock. Don't worry thoug, when the CLR shuts down, unmanaged resources will be released, but buffers may not be flushed, and final writes may be lost.
good to know nothing is leaked permanently. I can sleep better now.
Hope that helps! -Chris
"Daniel Jin" <Da*******@disc ussions.microso ft.com> wrote in message
news:F9******** *************** ***********@mic rosoft.com... Actually, there are other cases when a finalizer may not be run: -When the appdomain that contains the object is "rudely" unloaded -There is a finalizer that is starving the finalizers by hogging the
finalizer thread (which has a timeout) -The finalizer thread times out because of too many finalizable objects
on the queue. interesting. I wasn't aware of the last two points. I guess the doc was right in the cautious approach. more reason not to rely on finalizers too much. thanks for the information.
is there a reason why there's a timeout on the finalization thread? is it to avoid a hanging finalizer, like one that is in a deadlock.
Exactly. Good example in the August msdnmag .NET Matters column. Don't worry thoug, when the CLR shuts down, unmanaged resources will be
released, but buffers may not be flushed, and final writes may be lost.
good to know nothing is leaked permanently. I can sleep better now.
Everything is still under control of the OS. This has been the case for
Win32 processes since NT3.1, and .NET apps pick it up as well for system
resources.
bob This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Susan Baker |
last post by:
Hi,
I'm just reading about smart pointers..
I have some existing C code that I would like to provide wrapper classes
for. Specifically, I would like to provide wrappers for two stucts
defined as ff:
typedef struct {
float *data ;
int count ;
|
by: ozbear |
last post by:
This is probably an obvious question.
I know that pointer comparisons are only defined if the two pointers
point somewhere "into" the storage allocated to the same object, or if
they are NULL, or one-past the end of the object as long as it isn't
dereferenced.
I use "object" in the standard 'C' sense.
Is there some special dispensation given to comparing two pointers
|
by: Mikhail Teterin |
last post by:
Hello!
I'd like to have a variable of a pointer-to-function type. The two possible
values are of type (*)(FILE *) and (*)(void *). For example:
getter = straight ? fgetc : gzgetc;
nextchar = getter(file);
What type should I give to `getter' so that the compiler does not issue
|
by: Lance |
last post by:
VB.NET (v2003) does not support pointers, right? Assuming that this is true, are there any plans to support pointers in the future? Forgive my ignorance, but if C# supports pointers and C# and VB.NET get compiled into the same code, then I don't understand why VB.NET can't support pointers
Thanks for any info
Lance
|
by: Alf P. Steinbach |
last post by:
Not yet perfect, but:
http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf
http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip
To access the table of contents, use the "Bookmarks" tab in Adobe
Acrobat.
Comments, corrections, praise, nits, etc., are still welcome!
| |
by: Jim Langston |
last post by:
Someone made the statement in a newsgroup that most C++ programmers use
smart pointers. His actual phrase was "most of us" but I really don't think
that most C++ programmers use smart pointers, but I just don't know.
I don't like them because I don't trust them. I use new and delete on pure
pointers instead.
Do you use smart pointers?
|
by: Josefo |
last post by:
Hello, is someone so kind to tell me why I am getting the following
errors ?
vector_static_function.c:20: error: expected constructor, destructor,
or type conversion before '.' token
vector_static_function.c:21: error: expected constructor, destructor,
or type conversion before '.' token
|
by: J Caesar |
last post by:
In C you can compare two pointers, p<q, as long as they come from the
same array or the same malloc()ated block. Otherwise you can't.
What I'd like to do is write a function
int comparable(void *p, void *q)
that will take any two pointers and decide whether they can be compared
or not.
I really can't think how to do this - any suggestions?
|
by: Boris |
last post by:
I had a 3 hours meeting today with some fellow programmers that are partly
not convinced about using smart pointers in C++. Their main concern is a
possible performance impact. I've been explaining the advantages of smart
pointers endlessly (which are currently used in all our C++ software; we
use the Boost smart pointers) as I'm seriously concerned that there is a
shift to raw pointers. We are not developing system software but rather...
|
by: StevenChiasson |
last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller.
This is more or less, your standard dynamic address book program. Adding, and listing work just fine. However, deleting, editing and viewing relies on member function retAddress. This function returns an array of pointers that are pointing to created objects. In action, all it...
|
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,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |