DEV Community

Cover image for C# Object Initialization and Constructor
Dany Paredes
Dany Paredes

Posted on • Updated on

C# Object Initialization and Constructor

When we have few fields in a class and want to initialize every field in a constructor it should become a little bit messy and maybe we need a few constructors.

public class User
    {
        public string Name;
        public List<string> Roles;

        public User(string name)
        {
            Name = name;
        }

        public User(string name, List<string> roles)
        {
            Name = name;
            Roles = roles;
        }
    }

Enter fullscreen mode Exit fullscreen mode

We can use object initializer syntax, to initialize our properties and reserve the constructor, for the cases when we really need them, removing the constructor our class looks cleaner.

public class User { 
   public string Name; 
   public List<string> Roles; 
}
var test = new User
{
   Name = "Dany",
   Roles = new List<string>() {"Admin", "Normal"},
   Id = 12
};

Enter fullscreen mode Exit fullscreen mode

Read more in https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
Happy C#

Photo by Chris Scott on Unsplash

Oldest comments (0)