Learning to Code — Part 8a: More on Classes

Scott Rosenbloom
7 min readJul 31, 2018

--

DESTRUCTORS

The SoloLearn app now goes into what, effectively, is the opposite of a constructor (which is the instantiation of a class), which is a destructor. Destructors are automatically invoked when an object is destroyed or deleted. They then list the following four attributes of destructors:

  • A class can only have one destructor.
  • Destructors cannot be called. They are invoked automatically.
  • A destructor does not take modifiers or have parameters.
  • The name of the destructor is exactly the same as the name of the class, prefixed with a tilde (~), as in the following:
class Dog {
~Dog() {
//code statements
}
}

Destructors are useful for releasing resources before coming out of a program, such as closing files or releasing memory. In other words, the constructor would initialize and open the files. Then, when the program ends, the destructor would close the files. The following shows how a destructor is automatically invoked:

class Dog {
public Dog() {
Console.WriteLine(“Constructor”);
}
~Dog() {
Console.WriteLine(“Destructor”);
}
}
static void Main(string[] args) {
Dog d = new Dog();
}

Here’s the SoloLearn explanation for what happens with the code above:

When the program runs, it first creates the object, which calls the constructor. The object is deleted at the end of the program and the destructor is invoked when the program’s execution is complete.

STATIC

They keep mentioning the keyword static, and while I keep looking it up everytime I see it, they now go into a full explanation. Members of a class can be declared as static, meaning they belong to the class itself, as opposed to individual, object instances. No matter how many objects of the class are created, there’s only one copy of the static member.

class Cat {
public static int count = 0;
public Cat() {
Count++;
}
}
static void Main(string{} args) {
cat c1 = new Cat();
cat c2 = new Cat();
Console.WriteLine(Cat.count);
}

When executed, here’s what happens:

  • A class is created called Cat.
  • Within it, a member variable called count is declared, with a data type of integer, and an initial value of 0. This member is public, meaning it can be accessed by any other member within this class, or by another assembly that references it. Additionally, it is static, meaning it belongs to the Cat class itself, and not to any instantiation of the Cat class.
  • Also within the Cat class is a method called Cat which, when called, increments the current value of the variable count by 1.
  • Within the Main method, first a new object of the Cat type is instantiated with the name c1. When that happens, the method called Cat (within the class called Cat) is called, and the variable count is incremented from it’s current value of 0 to 1.
  • The next line within the Main method creates another new object of Cat type with the name c2. When that happens, the method called Cat (within the class called Cat) is called, and the variable called count is incremented from it’s current value of 1 to 2.
  • Then, printed to the screen, is the current value of the variable count, within the Cat class (which is 2).

The point is that the count variable is shared between all objects, and is not, therefore, reinitialized back to 0 each time a new object of Cat type is instantiated. The SoloLearn app is clear to point out that you can only access static members using the class name itself, and that you’ll get an error if you try to access them via an object of that class.

Similarly with static methods, they can only access static members. In the following code, you can see that the Main method is static. Therefore, any methods called directly from the Main method must also be static.

class Dog {
public static void Bark() {
Console.WriteLine(“Woof”);
}
}
static void Main(string[] args) {
Dog.Bark();
}

When executed, the Bark method within the Dog class is called, and Woof is printed to the screen. The first comment within the Comments section also makes a very good point:

  • If you’re calling another static method from the Main method, then you can call it directly without instantiation (i.e. ClassName.FunctionName).
  • If you’re calling another method from the Main method, which is not static, you need to instantiate it first (i.e. ClassName ObjectName = new ClassName();), and then call the method (i.e. ObjectName.NonStaticMethodName).

CONSTANTS

Lastly, the app covers constant members which are static by definition.

class MathClass {
public const int ONE = 1;
}
static void Main(string[] args) {
Console.Write(MathClass.ONE);
}

When executed, this code prints 1 to the screen, as it is calling the class called MathClass, and accessing the value of the variable called ONE. But I’m not sure what const is used for…to Google!!!

According to Dot Net Perls, and the post called Const, it simply means that the variable cannot be assigned another value later, because it is initiated with a value. That value can also not be manipulated. So, whereas you can have:

const string _html = “.html”;

If you try to assign it another value later…

_html = “”;

…it will cause an error

STATIC CONSTRUCTORS

On the same page, they go through static constructors which, when declared, can initialize static members of the class. The static constructor is automatically called once we access a static member of the class, like this:

class SomeClass {
public static int X { get; set; }
public static int Y { get; set; }
static SomeClass() {
X = 10;
Y = 20;
}
}

In the code above, if the value of the X variable is accessed from within the SomeClass class (such as with SomeClass.X), the get; function will automatically call the SomeClass method (which is a static constructor) getting the value of X (which is 10), and will then set the X from where it’s coming to 10. In other words, the value SomeClass.X is 10.

I needed a bit more information and, within the comments, found one responder, named Tom McCurdy, created a great YouTube video called C#: Static vs Non-Static: SoloLearn Connar’s Static Member Question. He also created a follow-up video that was also really useful called C#: Basic Class with Static and Non-Static Properties.

STATIC CLASSES

In the previous sections, we talked about individual members within a class being static. The SoloLearn app now goes through how an entire class can be declared as static as well. It’s important to note, however, that static classes can contain only static members. Also, you cannot instantiate an object of a static class, because only that one instance of the static class can exist within the program.

As static classes are good for combining logical properties and methods, a good example of a static class is the Math class (which is built-in). It contains various useful properties and methods for mathematical operations, such as the Pow method, which raises a number to a power:

Console.WriteLine(Math.Pow(2,3));

When executed, this calculates 2 to the 3rd power, which equals 8 (which is printed to the screen). Here’s a list of additional static methods and properties within the static Math class:

  • Math.PI — the constant PI
  • Math.E — represents the natural logarithmic base e
  • Math.Max() — returns the larger of its two arguments
  • Math.Min() — returns the smaller of its two arguments
  • Math.Abs() — returns the absolute value of its argument
  • Math.Sin() — returns the sine of the specified angle
  • Math.Cos() — returns the cosine of the specified angle
  • Math.Pow() — returns a specified number raised to the specified power
  • Math.Round() rounds the decimal number to it’s nearest integral value
  • Math.Sqrt() — returns the square root of a specified number

The Array class also has the following static methods:

int[] arr = {1, 2, 3, 4};
Array.Reverse(arr); //arr now equals 4, 3, 2, 1
Array.Sort(arr); //arr now equals 1, 2, 3, 4 once again

The String class has the following static methods:

string s1 = “some text”;
string s2 = “another text”;
String.Concat(s1, s2); // combines the two strings
String.Equals(s1, s2); // returns false

DateTime is another class with the following static methods:

Date.Time.Now; // represents the current date and time
DateTime.Today; //represents the current day
DateTime.DaysInMonth(2016, 2); // returns the number of days in the specified month

Another point they mention is that we have actually been using a specific static class, along with some static methods. It is the Console class. We have used it like this:

Console.WriteLine(); prints a value to the screen
Console.ReadLine(); gets user input

The also mention one last static class, which is Convert, which is used to convert value types.

In the second half of this part, we’ll go through:

  • this and readonly, which refers to the current instance of the class, and the prevention of a member of a class from being modified after construction,
  • Indexers, which allows objects to be indexed like an array, and
  • Operator Overloading, which is the ability to redefine operators (like the plus sign) for custom actions.

Please let me know if I missed anything, or messed anything up. Here’s a link to the previous article: Learning to Code — Part 7b: Arrays & Strings.

By the way, if you’re looking for more information about me, please visit my site at BIMuzer.com!

--

--