AFAIK, all types are derived from
System.Object class.
Considering this, how can I calculate how many bytes the following code is taking:
Employee emp = new Employee("emp_name");
and
List<string> empList = new List<string>();
What is the best and appropriate method to calculate the bytes they are taking?
You can use the C#
sizeofoperator but it is quite limited because you have to specify the type at compile time and it can only be used on built-in types. For youEmployeeclass you can add these together to determine the size of class. However, all reference types in theEmployeeclass (likeString) are separately allocated on the heap and you will have to add the size of these objects to get the total size.With some IL trickery you can use the following method to compute how many bytes a value type (
struct) requires. For reference types it will always return the size of a reference (4 bytes on 32 bit):However, even using
sizeofto compute bytes isn’t entirely accurate. Objects on the heap will have an additional type handle which is like a vtable pointer in C++. Exactly how this is done is an implementation detail of the .NET runtime.