Creating instances in C# is a bit different because there’s a difference between value types and reference types. You’ll be able to navigate your objects with ease after this episode.

You first learn how to place your C# classes in their own .cs files and how this is different than creating separate .cpp and .h files as in C++. You also have the ability in C# to declare your classes, structs, and even methods to be partial which allows you to divide them between multiple files.

Then, you learn how to determine which types are value types and which are reference types. This is a new concept that at first seems similar to references in C++ but it’s actually a very fundamental difference in C#.

Value type variables in methods always go to the stack directly and get their own instance. So if you have two instances of a struct type and you assign one of the variables to the other, what you end up doing is copying the contents of the one to the other.

But a reference type just gives you a pointer that lives on the stack which actually points to the instance in the heap. C# doesn’t call this a pointer and it ends up looking very much like a reference in C++. If you create two instances of a class type and assign one of the variables to the other, what you end up with is both variables now point to the same instance. The values of the data inside the instance did not change and in fact, one of the instances will now be eligible for garbage collection.

That’s all there is really to deleting instances in C#, you just forget about them and the garbage collector will clean it up at some later point. You can always implement Disposable and call the Dispose method if you have any action you need to perform before then. Just make sure to call Dispose while your reference still refers to the instance.


What's on your mind?
On a scale of 0 to 10, how likely are you to refer us to friends?