C# : assign data to properties via constructor vs. instantiating

后端 未结 3 1071
孤城傲影
孤城傲影 2020-12-22 19:04

Supposing I have an Album class :

public class Album 
{
    public string Name {get; set;}
    public string Artist {get; set;}
    public int Y         


        
3条回答
  •  执笔经年
    2020-12-22 19:32

    Second approach is object initializer in C#

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

    The first approach

    var albumData = new Album("Albumius", "Artistus", 2013);
    

    explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

     var albumData = new Album
            {
                Name = "Albumius",
            };
    

    Object initializer would translate into something like:

    var albumData; 
    var temp = new Album();
    temp.Name = "Albumius";
    temp.Artist = "Artistus";
    temp.Year = 2013;
    albumData = temp;
    

    Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

    As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

提交回复
热议问题