Home > Backend Development > C++ > How Can I Determine the Size of an Object Instance in Bytes in C#?

How Can I Determine the Size of an Object Instance in Bytes in C#?

Susan Sarandon
Release: 2025-01-10 16:11:42
Original
800 people have browsed it

How Can I Determine the Size of an Object Instance in Bytes in C#?

Get object size (in bytes) in C#

How to determine the size (in bytes) of any object instance in C#? This is especially useful when you need to determine the aggregate size of various collections of objects.

Get object size

To get the size of an instance, you can use a series of undocumented tricks. Keep in mind that these methods are not guaranteed to always work and may change in future .NET updates.

Use TypeHandle

You can use the TypeHandle internal structure to access the "base instance size" field of a type. Here’s how:

<code class="language-csharp">object obj = new List<int>(); // 使用您需要的对象替换
RuntimeTypeHandle th = obj.GetType().TypeHandle;
int size = *(*(int**)&th + 1);
Console.WriteLine(size);</code>
Copy after login

This method will provide a base instance size for most common types. However, arrays, strings, and StringBuilder require additional calculations to account for the elements they contain.

Extension method considerations

While there are no known extension methods explicitly for determining object size in bytes, you can develop one yourself if desired.

The above is the detailed content of How Can I Determine the Size of an Object Instance in Bytes in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template