Hi Folks,
In this post, we talk about how to assign data to properties when instantiating an object in c#.
Suppose you have a class like
public class Album { public string Name {get; set;} public string Artist {get; set;} public int Year {get; set;} public Album() { } public Album(string name, string artist, int year) { this.Name = name; this.Artist = artist; this.Year = year; } }
You can create an instance of Album class either via the constructor e.g.
var albumData = new Album("Albumius") { Artist = "Artistus", Year = 2013 };
After compilation, this is similar to the following:
var albumData = new Album("Albumius"); albumData.Artist = "Artistus"; albumData.Year = 2013;
That’s all for now. Till next time, happy software development.
References
C# : assign data to properties via constructor vs. instantiating. stackoverflow. https://stackoverflow.com/questions/19138195/c-sharp-assign-data-to-properties-via-constructor-vs-instantiating