Home  >  Article  >  Backend Development  >  C# object initializer

C# object initializer

WBOY
WBOYOriginal
2024-09-03 15:06:25322browse

Object initializer in C# lets you enable to assign values to the class variable. If you use an object initializer in C#, we do not require the constructor to assign values of the class member variable. We can assign value to the variable while creating the instance of the class. It has a different syntax than the constructor. In short, it is a new form to initialize the object in C#; in the coming section, we will discuss more the object initialize and their implementation in detail for better understanding and usage.

Syntax

As it’s named, suggest it is used to initialize the object of the class in C#. It is more easy and simplified; let’s see its syntax for better understanding and its usage while creating the application in C# see below;

Class_name std = new Class_name() {
// indside this we can initialize the object withour using the constructor.
};

As you can see in the above syntax, we are trying to create the object of the class, followed by the new keyword that we commonly used in C# to create the object. After that, we are trying to assign the values to the object inside the ‘{}’ curly braces. Let’s see one practice syntax for beginners to implemented quickly see below;

Example:

Demo d = new Demo() { name  = "demo sample"
};

In the above lines of syntax, we have just shown how to use this while programming. In the coming section, we will discuss its internal working more in detail to improve the application.

How to initialize an object in C#

As we have already known now, object initialization is the process of creating the object of the class or collection, but there is some more advantage of doing this in practice. While creating the object, we can assign a value or initialize the class variable or class member without using the constructor in C#. We have the same way for creating the object, but to initialize them, we have somewhat different syntax in C#. To create the object, we still use the ‘new’ keyword. In this section, we will discuss the syntax for object initialization in more and more detail. Also, one practice example for beginners to make use of this while programming.

Let’s discuss its signature in more detail; see below;

Signature:

Demo d = new Demo() { name = "dummy name",
roll_num = "200",
city = "some city"
};

In the above sample, we are using the ‘new’ keyword apart from some changes we have made in object initialization. To make use of object initialization in C#, we have to follow some rules, which are defined as follows:

1. We first have to create the object of the class or collection which we want, as we normally do in C#. To create the new object in C#, we make use of the ‘new’ keyword.

2. Immediately after the object creation, we are bound to assign the values to the class variable if you want to implement object initialization in C#.

3. for this, we have to make use of ‘{}’ braces in C#. Inside these {} braces, we can pass our variable, which we want to give values. It is not mandatory to pass or assign values to all the variables to the object initialization; it depends upon the requirement. We have given force here because we are not using any constructor here to assign them the values.

4. Object initialization also reduces the lines of code that is required to initialize the variable. Also, we do not require to create the default and parameterized constructor for this. It also makes our code more readable and less in the number of lines.

5. After this, we can assign any type of variable to it. Whether it is a string, number, or anything.

6. Also, at the end of the {} braces, we have to end this with a ‘;’ semicolon to make t work. Otherwise, it will give us a compile-time error saying missing or expected ‘;’ at the end.

Now we will see one sample example for beginners to understand its internal working and implementation in a real scenario see below;

Example:

public class Employee
{
public int EmployeeId { get; set; }
public string Employeecity { get; set; }
}
class Demo
{
static void Main(string[] args)
{
System.Console.WriteLine();
Employee emp = new Employee() { EmployeeId = 100,
Employeecity = "indore"
};
}
}

In the above example above we are creating one class named ‘Employee’, which is going to contain the employee information for the record. Inside this, we are storing two-variable ‘EmployeeId’ and ‘Employeecity’ inside the class. After that, we access this variable; we have one more class named ‘Demo’, which contain the Main() method inside Inside this method, we are making use of object initialization in C#, by the use of it, we are trying to initialize the variable of the class see above. After that, we can either store them in db or simply print them using a console log.

Example

1. Trying to show employee data using object initializer in C#. This is a sample example for beginner to understand its implementation. We can create any number of objects we want using object initializer and store data.

Example:

public class Employee
{
public int EmployeeId { get; set; }
public string Employeecity { get; set; }
public int Employeesalary { get; set; }
public string Employeename { get; set; }
public string Employeeaddress { get; set; }
public string Employeedepartment { get; set; }
}
class Demo
{
static void Main(string[] args)
{
System.Console.WriteLine("Demo to show object initializer in C# !!");
Employee emp = new Employee() { EmployeeId = 100,
Employeecity = "indore",
Employeesalary = 15000,
Employeename = "Amit vyas"   ,
Employeeaddress = "1009 strre",
Employeedepartment = "Account"
};
System.Console.WriteLine("Prinitg the values from the object ::::");
System.Console.WriteLine("emp id is:: " + emp.EmployeeId);
System.Console.WriteLine("emp city is:: " + emp.Employeecity);
System.Console.WriteLine("emp salary is:: " + emp.Employeesalary);
System.Console.WriteLine("emp name is:: " + emp.Employeename);
System.Console.WriteLine("emp address is:: " + emp.Employeeaddress);
System.Console.WriteLine("emp department is:: " + emp.Employeedepartment);
}
}

Output:

C# object initializer

Conclusion

By using object initialization, we can simply assign value to a variable without using constructors in C#. We can assign them value while creating the object only. its syntax is a bit different from the existing one we have like for the constructor. This makes the line of code less more readable or understandable.

The above is the detailed content of C# object initializer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# object senderNext article:C# object sender