Struct vs class
- Game Development course
- Expert
- Lesson 9/47
- 4 min
Learn the memory difference between struct and class.
The struct and class difference
A struct is a value type; its value is stored directly and it usually sits on the stack. A class is a reference type; its object is kept on the heap and only the reference sits in the variable. This difference directly affects memory usage.
public struct Nokta
{
public int x;
public int y;
}The Nokta above is a value type.
Which type to choose?
For small and frequently copied data a struct is suitable; this way no heap allocation is made. For large objects or ones that need inheritance a class is used. Choosing the right type prevents needless allocations.
public class Nesne
{
public int x;
}
// Nokta is a value type, Nesne is a reference typeThe smaller the data, the more a struct makes sense.
Practice Work with a struct
In the Start method of the class StructOrnek, create a variable of type Nokta and assign the value 2 to its x field. Print the text "Nokta x: " joined with the x field using Debug.Log. Also define the Nokta structure with its x field as a value type.
Starter code
using UnityEngine;
public class StructOrnek : MonoBehaviour
{
void Start()
{
// Nokta tipinde bir degisken olustur, x alanina 2 degerini ata
// "Nokta x: " metnini x alani ile birlestirip yazdir
}
}
// Nokta adli yapiyi deger tipi olarak tanimlaSample solution
using UnityEngine;
public class StructOrnek : MonoBehaviour
{
void Start()
{
Nokta n = new Nokta();
n.x = 2;
Debug.Log("Nokta x: " + n.x);
}
}
public struct Nokta
{
public int x;
}Expected output
Nokta x: 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main memory difference between struct and class?
- struct does not use memory
- struct is stored on the heap, class on the stack
- struct is stored as a value type, a class object sits on the heap Correct answer
- Both are always stored on the heap
Explanation: A struct carries its value directly; a class variable references the object on the heap.
2 Define the value type with struct
public ____ Nokta
{
public int x;
}
public struct Nokta
{
public int x;
}
Explanation: Value types are defined with the struct keyword; class gives a reference type.
3 Memory type terms
| Term | Meaning |
|---|---|
struct |
A value type |
class |
A reference type |
Değer tipi |
The value is stored directly |
Referans tipi |
It points to the object on the heap |