Viewing a single comment thread. View all comments

Truen1ght t1_ixg95ul wrote

CLASS vs STRUCT

------------------------------

A class is a file that contains a bunch of operations it can perform, and a bunch of things it contains. The operations it can perform are called "methods" or "functions" (both are accurate, but maybe you've only heard one of the two terms. they are interchangeable).

By default, most things within a class have private scope, meaning only the class itself can perform operations listed within the class, or access/edit the things it contains.

A struct is nearly the same thing as a class, but by default everything is publicly scoped. That means that things outside of this class can perform the operations listed by the struct, or access/edit the things held by the struct.

So, truthfully, there are only 2 real differences between the struct and the class :

  1. using either the keyword "struct" or "class"
  2. the default scoping. public for a struct, private for a class.

So why are there two things? The struct came first from way back when, long before C# ever existed. The class came later, when people became better programmers and decided "yeah, maybe by default I should hide stuff from other structs/classes so that I'm less likely to accidentally change something I shouldn't". The struct is a holdover from original C.

​

CONSTRUCTOR and DESTRUCTOR

----------------------------------

A constructor is a special method that all classes and structs have. If you do not explicitly declare this method within your class or struct, there is a default constructor that is provided instead. You cannot have a class or struct without a constructor method, because then there is no way for your program to create that class or struct before you would try to use it.

The job of the constructor is solely for creating your class or struct.

The opposite of the constructor is the destructor. Like the constructor, your class or struct must have one, and if you don't declare it explicitly within your class/struct, a default one is provided for you.

The job of the destructor is to delete the class/struct you created earlier, so that the memory it used while your program was running doesn't stay allocated. You may have heard the term "memory leak", that is what a destructor is meant to prevent. If you "leak" enough memory, eventually your computer will become unresponsive because it has no available RAM to do things. The only way to resolve the problem in that case is to restart your computer, which automatically clears out everything in RAM, freeing it up for use.

​

Hopefully this explains it well enough for you.

2