0

I have seen in a code a use of braces to directly inform the values of the variables of the concerned class when creating a new instance.

Exemple (see employee3)

class Program
{
    static void Main(string[] args)
    {
        //I KNOW THIS.
        //Employee employee1 = new Employee(100, "Mike", 2000, 3);

        //I ALSO KNOW THIS.
        Employee employee2 = new Employee();
            employee2.ID = 101;
            employee2.Name = Henry;
            employee2.Salary = 3000;
            employee2.Experience = 4;

        //BUT THIS IS THE FIRST TIME I HAVE SEEN THIS.
        Employee employee3 = new Employee()
            { ID = 102, Name = "John", Salary = 3000, Experience = 5 };
    }


class Employee
{
    //Employee(iD, name, salary, experience)
    //{
    //    ID = iD;
    //    Name = name;
    //    Salary = salary;
    //    Experience = experience;
    //}

    //Employee() { }

    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public int Experience { get; set; }
}

What do these braces mean, what are they called, can they be otherwise useful...

Een Amok
  • 107
  • 2
  • 10

1 Answers1

1

They are used to initialise fields on the Employee object instance.

https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.