0

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 });
aaron
  • 30,879
  • 5
  • 34
  • 79
lost9123193
  • 9,040
  • 22
  • 62
  • 100
  • 1
    Also, you don't need to do `new WeaponData() { }`, just `new WeaponData { }` – Camilo Terevinto Nov 02 '17 at 00:25
  • Take a look at Microsofts documentation: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers – Rhexis Nov 02 '17 at 00:25

2 Answers2

3

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);
Kenneth
  • 27,326
  • 6
  • 58
  • 82
0

In this case, the weapon class has a no args constructor which is being called, in the same line, its initialising the id property with a value of 12. Its just another way of initialising the object

Colonel Mustard
  • 1,382
  • 1
  • 17
  • 41