How can I get the memory address of a feilds in C#?
created an object from a class in C#. Is it possible to retrieve its memory location and address using C# code?
i have tried this code but i got error at this line
IntPtr address = GCHandle.AddrOfPinnedObject(handle);
of the code
`26 Replies
do you have a specific goal or are you just experimenting?
what's the actual error?
no i just want to excrement
i will send you the error
Error CS1501 No overload for method 'AddrOfPinnedObject' takes 1 arguments C#ForBeginners D:\Projects\C#ForBeginners\C#ForBeginners\Program.cs 53 Active
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.gchandle.addrofpinnedobject?view=net-8.0
it's an instance method of GCHandle, not static
also, fwiw this is certainly not "C# for beginners"
you will probably never have to do something like this in a real program
this means that i have to create a new object
GCHandle,
but you have one
i just want to experiment do you have like some other way to experiment the memory address of a feild
no, because this is very very uncommon to do in C#
aha
the memory address of a field isn't useful information in 99.9% of cases
ok got the point all what i know about this that objects and there members got stored in the heap
yes, instances of classes are always on the heap
i have another small question do i have to learn somthing about the diffreance between the heap and the stack
it doesn't really matter for beginners
that becomes more important to think about when you start optimizing code for high performance
in the matter of fact i am going to use c# for web development ASP.NET , Core and other related to web
then you can quite safely ignore anything related to
IntPtr
and GCHandle
for a long long while, and stack/heap too tbh.this are handled using browsers in that case corect
$itdepends
ASP.NET is primarily a server component
in terms of web development C# code usually runs on the server only
the only exception is blazor webassembly which is still pretty immature and not a great option for frontend
OK so i don`t have to give any concentration in CG class and optimization of the code
that's not what i said
at some point you will probably have to care about optimization, but if you're just starting to learn then it isn't important
it should certainly not be a primary concern as a beginner
it's more important to make it work first, then you can worry about making it fast
ok thank you all @Jimmacle @Pobiega
Also note that the printed address in your example is tenuous, because after you free the handle the object gets unpinned, and the GC is once again free to move it around in memory however it wishes. (probably won't though, it's designed to be as lazy as possible)