-1

System.Object--> System.ValueType--> System.Enum, System.Int16, System.Int32, System.Int64...

The ValueType is an abstract class ValueType, but why Int16,Int32,Int64 were made struct ?

Also another question is that why these struct were inherited from System.ValueType and why not from object class itself ? From my study I understood this much only that , the role of System.ValueType is to ensure that the derived type is allocated on the stack rather than the garbage collected heap.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
ram sam
  • 3
  • 1

1 Answers1

1

Why would they be objects? The whole point is to get rid of the baggage Object brings (vtable, everything) and keep an object so lightweight you can afford to copy it around when needed.

Base types like integers are prime candidates to be value types, because they fit in a register and are easy to pass around as such.

Forget about heap and stack, they're iffy concepts as it is in C++, you're using C# now. Everything lives on the various garbage collection queues (or in registers, especially for the x64 compiler).

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • "get rid of the baggage Object brings " apart from vtable what are the other things that you are talking about ?can you please specify a bit ! Also what makes ValueType lightweight object class ? – ram sam May 05 '15 at 02:07
  • It's immutable for one, so it's extremely easy, cheap and safe to parallelize. It's lightweight because it literally has nothing but the data you need, no vtable, no monitor (`lock`), nothing. Value types can increase the performance of your app by a lot if used right (few people use them right though). – Blindy May 05 '15 at 02:53
  • @Blindy what is immutable? Definitely you are not talking about c# structs... which unfortunately are mutable... – Alexei Levenkov May 05 '15 at 03:00
  • 1
    @Alexei, right, I meant the most common way to use value types is to make them immutable by design. They tend to be really good for it because without the extra memory being used by `Object`, short lived objects get collected very quickly. You are of course right that it's not a requirement for them to be immutable. – Blindy May 05 '15 at 04:19