This MVA video does an excellent job of explaining the difference. This post is a short summary of the video.
The most important thing to understand is passing by reference versus passing by value. The example I use for explaining the difference between pass by reference and pass by value is this: You go to an art gallery and buy an original work of art. When you take it home, your 2-year-old scribbles all over it with crayon. The original work of art is forever changed. That's passing by reference. But if you were to buy a print of the original work of art which your 2-year-old then scribbles on, the original work of art is not affected. Although it may suck for you that you paid good money for a print which is now messed up, the original work of art remains intact and more prints can be made from it. That's passing by value.
If you've looked at structs before, you know that a struct looks and acts a lot like a class. But as is pointed out in the video, there are some major differences. So here is the promised summary of the video.
1. Structs are values types and classes are reference types. Thinking of my example above, this means that when changes are made, only a copy is changed and not the original values in a struct. But with a class, whatever values you change are changed within the class itself. The MVA video does a great job of demonstrating this by code. I copied the code and put it on GitHub so I could see the whole thing at once. I just got tired of rewinding and fastforwarding when I wanted to see something. Just remember, this is not my code but the code from the MVA video.
2. Structs are passed on the stack and classes are passed on the heap. When a copy of a struct is passed onto the stack, the whole data structure is passed. (This is also means structs should be smaller data structures than classes.) When a class is passed on the heap, a copy of the memory address is passed. While this makes the process more efficient than passing the entire data structure, it also means that the method receives a copy of the instance of the class and, thus, has access to change the class itself.
3. What is the stack and what is the heap? Here is a great article. I won't try to reinvent the wheel. Just read this.
4. What is with the hashtags? It just means you can specify a block of code, a region, like the struct, that can be collapsed while you look at other code. I added in the regions to the code on GitHub, so you can try it out there.
No comments:
Post a Comment