How to Initialize Struct – C# Struct Initialization Guide
In C#, there are multiple ways to declare and initialize structs. While using just one method is often enough, it's common to encounter different initialization styles in real-world code. This guide summarizes the most common approaches, including how to handle struct arrays and lists.
Struct Declaration
struct Item
{
public string name;
public int price;
public string desc;
}
1. Declare First, Assign Later
This is the most straightforward method. Declare the struct first, then assign values to its fields one by one.
Item item;
item.name = "Fireball";
item.price = 100;
item.desc = "Deals fire damage to the enemy.";
Note: Structs are value types, so you can declare them without new. However, you must initialize all fields before use, or you'll get a compile-time error.
2. Use new and Assign Fields
Item item = new Item();
item.name = "Fireball";
item.price = 100;
item.desc = "Deals fire damage to the enemy.";
This is functionally the same as method 1, but using new ensures the struct is fully initialized with default values (e.g. 0, false, null).
3. Object Initialization Syntax
You can initialize a struct and set values all at once using curly braces:
Item item = new Item
{
name = "Fireball",
price = 100,
desc = "Deals fire damage to the enemy."
};
You can also write it in a single line:
Item item = new Item { name = "Fireball", price = 100, desc = "Deals fire damage to the enemy." };
Struct Array Initialization
When you create a struct array using new, all elements are initialized with default values. Then, you can assign values just like before.
Item[] items = new Item[3];
// Method 1: Field-by-field assignment
items[0].name = "Fireball";
items[0].price = 100;
items[0].desc = "Deals fire damage to the enemy.";
// Method 2: Inline initialization
items[1] = new Item
{
name = "Ice Shot",
price = 120,
desc = "Freezes enemies for 2 seconds."
};
In the above example, the first new creates the array, while the second new creates a struct instance and assigns values to its fields.
Struct List Initialization
You can use a List<Item> to hold multiple structs and initialize them in one step:
List<Item> items = new List<Item>
{
new Item { name = "Fireball", price = 100, desc = "Fire damage" },
new Item { name = "Ice Shot", price = 120, desc = "Ice damage" },
new Item { name = "Speed Boots", price = 80, desc = "Increases movement speed" }
};
Summary
Now you’ve seen several ways to initialize structs in C#. Whether you're assigning values one by one, using object initializer syntax, or working with arrays and lists, you can choose the method that best fits your use case.
