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
  • 39,695
  • 6
  • 46
  • 102
lost9123193
  • 10,460
  • 26
  • 73
  • 113
  • 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://learn.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
  • 28,294
  • 6
  • 61
  • 84
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,482
  • 2
  • 17
  • 42