Value Types and Reference Types - Structures
(Page 4 of 4 )
Before we wrap up our discussion of value and reference types, we have one important point about structures that we need to clarify. From our discussion of structures, we learned that we can create a structure and initialize its members using code like this:
struct Size
{
public intwidth;
public intheight;
}
Sizes;
s.width = 100;
s.height = 50;
Surprisingly enough though, C# allows you to create structures using thenewoperator:
Sizes = new Size();
But wait, structures are value types and the new operator is for reference types. What does this statement mean? Can we actually create a structure on the heap?
Well, how thenewoperator is used here is not the same as the one used with reference types. The structure is still created on the stack (not the heap). Thenewoperator here is used solely to trigger the constructor (the special method that initializes the data members). This constructor is special in that it is called a default constructor (does not take any parameter). With structures, this constructor is reserved for the runtime (which means that we cannot create our own default constructor in the structure). We can create non-default constructors though.
Conclusion: We can create two kinds of types in C#: value type (likebool,int,struct,enum) and reference type (class,interface,delegate). The value types are created on the stack and their value is popped out of the stack when the variable goes out of scope. Reference types are created on the heap and when there are no more variables referencing the object, it will eventually be cleaned up by the garbage collector. Understanding the difference between value types and reference types will help you create more efficient code and save you a lot of frustrating debugging time.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |