DEV Community

loading...

C# Object Initialization and Constructor

Dany Paredes
ex .NET guy, my last years building solutions with Vue, Angular, Sass, and Typescript.
・1 min read

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#

Discussion (0)