1

From very first day of my learning of OOPS I learned that a class is a logical entity which does not require any space.

But today I was just reading about Memory Management and found that the size of a Class in C# is not 0. The size of a class instance is determined by:

  1. The amount of data actually stored in the instance
  2. The padding needed between the values
  3. Some extra internal data used by the memory management

Since Empty class will not have any data so 1st point will be 0 but what are others two points here? Why size of an empty class is not zero?

John
  • 704
  • 3
  • 12
  • 29
  • 4
    See: [Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects](http://msdn.microsoft.com/en-us/magazine/cc163791.aspx). Pay attention to uses of "padding" and "header". – Ani Mar 26 '14 at 07:27
  • http://www.codeproject.com/Questions/177604/Size-of-a-class-in-c – Soner Gönül Mar 26 '14 at 07:29
  • @Ani , I think your comment should be in answer(accepted) with few more details... – PM. Mar 26 '14 at 07:56
  • here I found 1 article for same: http://www.geeksforgeeks.org/why-is-the-size-of-an-empty-class-not-zero-in-c/ – John Mar 26 '14 at 09:35

1 Answers1

2
  • "0" takes up some space itself to store - if you store it as a 4 byte number it takes up 4 bytes!
  • Of course this information about the class has to take up memory otherwise where would you read it from?

A C# "class" as defined on MSDN

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.

markmnl
  • 11,116
  • 8
  • 73
  • 109
  • Did you mean 32 bit number? – jmstoker Mar 26 '14 at 07:41
  • No, I said if it stores the size of the class as a 32 byte number and the size of the class's data is 0 this would take 32 bytes to store. – markmnl Mar 26 '14 at 07:48
  • I would advise if you are leaning C# and OOP not to worry about the internals of how a class is stored and used internally - it is irrelevant. – markmnl Mar 26 '14 at 07:50
  • A 32 byte number is an odd example to use and is more confusing than helpful. Who stores a 32 byte number when the largest native datatype is 8 bytes in length except for specialized needs. – jmstoker Mar 26 '14 at 07:57
  • Sorry I did originally intend to say 32bit, i.e. 4 bytes. but it is irrelevant, the points is it takes up memory. – markmnl Mar 26 '14 at 08:02