Saturday, March 02, 2024 00:53

Table of contents >> Data Structures > Other Data Structures

Other Data Structures

Surprisingly, you will notice that we have already used these data structures before, without knowing they were data structures: the class and the structure. Whenever we instantiate one of these, we are actually using it as a data structure (more or less). You may not know, but a structure is very similar to a class, in the way we declare and use it. Both can have field variables, both can contain methods, both can be instantiated, etc. The only difference between a class and a struct is the way they work internally. We haven’t learned about stack (no, not the stack data structure) and heap, but basically they are two different kinds of memory in the RAM of your computer, with different behaviors. So, a class, being a reference type, is stored as a pointer, a reference to some other place in the heap, where the actual value is stored. On the other hand, a structure, being a value type, is stored on the stack, and the variable holds the entire data itself, with all its fields, methods, etc. Another difference is the fact that reference types can be null (they point to no place in the memory), while value types always contain a value.

According to MSDN: “structs are typically used to encapsulate small group of related variables, such as coordinates of rectangle. Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.”

This means that whenever you just need to store simple data, a struct is perfect for the job. But if you find yourself adding functionality and logic to your structure, it would most likely be better to make it a class.

Now, lets see how we can use both these concepts as data structures:

As you can notice, at this point, we are actually storing data inside our newPoint and newSize variables. We could store names, addresses, whatever we would want.

The only “downside” compared to other data structures is the fact that if we want to store another field, we need to modify the class or struct itself. This means that once our code is compiled and executed, we cannot modify the structure of our class or struct. We cannot add another variable called “length” to our Size class. On the other side, for the other data structures (such as dictionary, list, etc), adding a new value to the class at runtime is just a matter of using the Add() method. The “advantage” is the fact of being able to store multiple data types in a single data structure, unlike arrays, lists, etc, and also having the possibility of acting upon that data (methods, functions, etc) internally.

Tags: , ,

Leave a Reply

Follow the white rabbit