Translate

Friday, July 5, 2013

get size of a type c# (How to find size of a class in memory c#)

Use System.Runtime.InteropServices.Marshal.SizeOf(Type t) to find the size of a type. See below for an example.

In project properties under build set Allow unsafe code










The code below uses the method Marshal.SizeOf() to find the size of the class Point

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            unsafe
            {
                var sizeinBytes = Marshal.SizeOf(typeof(Point));//size in bytes
                Console.WriteLine(sizeinBytes);//16
            }


        }


        [StructLayout(LayoutKind.Sequential)]
        public class Point
        {
            int x;//4 bytes
            int y;//4 bytes
            private int[] i = new int[10];//reference to an array will hold a 32 bit address (for a 32 bit address bus), which is 4 bytes
            AnyClass ac;//reference to a class will hold a 32 bit address (for a 32 bit address bus), which is 4 bytes
        }

        public class AnyClass
        {

        }

    }
}



No comments:

Post a Comment

Comments will appear once they have been approved by the moderator