Search code examples
c#object-initializers

Curly Braces in C# Method


I'm currently programming in C# and found this snippet in one of the tutorials.

What exactly do the curly braces in this method mean? Is it like a key value pair {id: 2}?

weapon = new Weapon(new WeaponData() { Id = 12 });

Solution

  • This is what's called an obect initializer. It allows you to set the values of properties right after the obect is constructed. It's equivalent to the following code:

    var weaponData = new WeaponData();
    weaponData.Id = 12;
    weapon = new Weapon(weaponData);