- Loading...
- No images or files uploaded yet.
|
|
Struct In-DepthI really had a hard time wrapping my brain around the struct "type", and how it tied in with classes and the whole .net class hierarchy. So I did some digging and was surprised at what I found out.
Another Way to Think About Struct
First of all, you have to think of struct as a keyword rather than a type. When you use it you are essentially defining a new class that has special behavior. Now forgive me because I am going to begin using the word class very loosely. When you define your own type using the struct keyword you are essentially creating a class, but implicitly your type inherits directly from the System.ValueType class. System.ValueType inherits directly from System.Object. So your new type is a class that inherits from System.ValueType.
Now from what I understand, inheriting from System.ValueType is what gives your class its special behavior, i.e. allocating on the stack rather than on the heap, instantiation w/o using the new keyword, etc. And along with this special behavior, you are also placing some heavy constraints on the new type, i.e. no default constructor, no support for compile-time initialization of instance fields, cannot be derived from, etc. I find that this is a very simple and clear way to think about structs. But, clearly there is more going on under the hood by the compiler and CLR.
Give this doc a quick read. (MSDN)
Surprise! Many Built-In Types Are Structs!
Look at the docs! Int32, Boolean, Double, Decimal, Byte, Short, Long, etc etc etc... they're all struct types, in other words, they're value types. They are structs, which means they inherit from System.ValueType, which gives them their familiar value type behavior. And these built-in value types are not the only struct types in the framework. Our lovely System.DateTime class is a struct type, and so are many others! |
Comments (0)
You don't have permission to comment on this page.