Programming in Unity – Types 1

Categories: Dev Journey

When I started with JavaScript I got used on using var for everything. At some point somebody showed me that TypeScript exists to typify JavaScript basically. I had no idea what he was talking about as the whole terminology of types wasn’t clear to me.

When I got into C# the first time I learned about string, float, int and bool and started to use these, thinking maybe var is just the lazy JavaScript way of creating new variables. After all I have learned that JavaScript simply is a scripting language, while C# is a programming language, so I thought things are just more elaborated within the C# context.

So C# is a strongly-typed language, which means at the same time that we must declare the type of a variable. 

Programs consists of two components in general, one is data in which the information which is going to be processed is stored; the other one is logic which defines the operations that are going to be performed on data.

All Programs consist of two components:

•  Data – Information to be processed and stored

•  Logic – Operations to be performed on data

Variables are on the data side. We can look at them as boxes to be filled with the specified content, the content may change (but not in type) and can be referenced. They may even kept empty at the beginning, but a type should already be held in mind. The way we declare the type of a variable defines how it is going to be stored on the computers memory.

Types classify data. They tell us…

•  … which kind of data is stored

•  … the amount of memory required

•  … the location in memory

•  … their minimum and maximum value

•  … the kinds of  operations permitted.

The var Keyword

At some point I started to see the var  keyword in C#, in the way that people just simply used it to declare fields, parameter and arguments. It seemed to me as if they were using the var keyword in the same lazy way I knew from JavaScript. But still there are some differences and people argue on when to use the var keyword and when not.

The var keyword was introduced in C# 3.0 and corresponds with the release of LINQ. It allows implicit typing. Although a variable needs to know what kind of type it is going to have and once set it’s not possible to change its type

var randomNumber = UnityEngine.Random.Range(0, numberToDisplay);

// the following statement casts an error:
randomNumber = "Hello World!"; 

In many cases it is optional to use the var keyword, while some programmers complain about other programmers overusing it, others love to use it for everything. In this area it comes back to conventions and consistency. 

To me it makes sense to use the type keyword I am going to use whenever I can, it reminds me of what I intend to do and I believe it also helps others to directly read what the purpose of this variable is going to be

Because the  var keyword corresponds with the release of LINQ it has to be used when working with LINQ. It also has to be used when working with anonymous types.

var enemy = new { name = "Monster", hitPoints = 100 };

Example using System.Linq;

private void AnonymousTypeExample()
        {
            var enemies = new[]
            {
                new { name = "Monster", hitPoints = 100},
                new { name = "Goblin", hitPoints = 200},
                new { name = "Beast", hitPoints = 250}
            };

            // sorts enemies alphabetically by name
            var enemyQuery =
                from enemy in enemies
                orderby enemy.name
                select enemy;

            foreach (var enemy in enemyQuery)
            {
                Debug.Log(enemy.name);
            }
        }

As the method doesn’t know about the type its necessary to stay with the var keyword.

Types of Memory

When a program is started it will be loaded onto the computer memory (RAM). Some data will be stored in Stack and some in the Heap. This area is still a bit abstract and new to me, but I try to note down what I have learned so far.

•  Stack

•  Allocated when compiled

•  Data are stored sequentially

•  Variable size must be known

•  Stack variables can’t be resized

•  Not subject to garbage collection

•  Linear data structure

•  Local variables only

•  Primitive data types

•  Very fast

•  Heap

•  Allocated during runtime

•  Data are stored randomly

•  Variable size can be unknown

•  Heap variables can be resized

•  Are subject to garbage collection

•  Hierarchical data structure

•  Allows to access variables globally

•  Arrays

•  Objects (Classes(When classes are instatitated they are called objects))

•  Size can be defined by User Input

•  Slower

Value Types: bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort

Reference Types: class, interface, delegate, object, string, array

Value types are stored on stack while reference types are stored in the heap. Sometimes value types can be stored in the heap as well, it depends on where they have been declared.

In the following example the value types would be stored in the stack.

public int AddFive(int pValue)
{
	int result;
	result = pValue + 5;
	return result;
}

The example now shows how it gets stored in the heap

public class MyInt
{
	public int MyValue;
}

public MyInt AddFive(int pValue)
{
	MyInt result = new MyInt();
	result.MyValue = pValue + 5;
	return result;
} 

Another example, because the more the merrier:

public Method1()
{
		// Line 1
		int i = 4;

		// Line 2
		int y = 2;

		// Line 3
		Class1 cls1 = new Class1();
}

Line 1: Will allocate a small memory in stack

Line 2: Will stack the allocation on top of the first memory allocation. Imagine boxes being stacked  on top of each other.

Line 3: Creates a pointer on the stack while the actual object is stored in the heap. Imagine it loosely like particles in a cloud.

Memory de-/allocation is done using LIFO (Last in First out). So we are moving always from the top of the stack. 

That’s it so far. I will get to the types beyond string, int, float and bool next.


Sources:

https://www.tutorialsteacher.com/csharp/csharp-data-types

https://www.guru99.com/stack-vs-heap.html

https://www.embedded-software-engineering.de/stack-und-heap–die-grossen-unbekannten-der-embedded-software-beherrschen-a-555738/

https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/

https://dev.to/tyrrrz/interview-question-heap-vs-stack-c-5aae

https://www.c-sharpcorner.com/article/stop-use-var-everywhere-and-think-before-use-underscore-with-private-variable-in/

«
»

    Leave a Reply

    Your email address will not be published.