What is object initializer in c#?
c#
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Yadagiri ReddyRank #773 · 3K reputationPosted Oct 27, 2014, 11:34 AM EDT
Ajay YadavRank #313 · 8.1K reputationPosted Oct 27, 2014, 6:06 PM EDT
Arunava BhattacharjeeRank #635 · 3.8K reputationPosted Oct 27, 2014, 7:53 PM EDT
It can be used to ensure double-checked locking in multi-threaded environment. It also improves atomicity. The object initializer returns the new object after it has initialized all of the members you told it to.This ensures that the object is never partially initialized. It will either be null or fully initialized, which is useful in multi-threaded scenarios.
Another benefit while creating anonymous objects while using LINQ Select statement, where you dynamically specify anonymous properties. It can be also used in joins.
Employee emp = new Employee { Name ="Arunava", Salary = "60000", Age=29 };