[C#] Object Initializer - overloaded constructor belong to the past

Today I want to explain the Object Initializer in use with C#, which is a best practice for C# developers. Unfortunately overloaded Constructors can be found to initialize Objects with different kinds of parameters.
Let's say we have a class called LogEntry:

public class LogEntry
{
    // Properties
    public string message { get; set; }
    public DateTime timeStamp { get; set; }
    public LogType logType { get; set; }

    // Default Constructor
    public LogEntry() { }
}

public static enum LogType
{
    Error, Warning, Info
}

The good old fashioned way to initialize an Object of Type LogEntry would be to write an overloaded Constructor for every possible parameter combination which would end up in a mess like this or similar:

public LogEntry(string message, DateTime timestamp, LogType logType)
{
        this.message = message;
        this.timeStamp = timestamp;
        this.logType = logType;
}

public LogEntry(string message, DateTime timestamp)
{
        this.message = message;
        this.timeStamp = timestamp;
        this.logType = LogType.Info;
}

public LogEntry(string message, LogType logType)
{
        this.message = message;
        this.timeStamp = DateTime.Now;
        this.logType = logType;
}

public LogEntry(string message)
{
        this.message = message;
        this.timeStamp = DateTime.Now;
        this.logType = LogType.Info;
}

This is very time intensive to create, hard to maintain if a new property is added and hard to read!

Better way: Object Initializer

To initialize a new Object of Type LogEntry with the Object Initializer, we can simply write the following:

string myMessage = "Message Text";
LogType msgLogType = LogType.Info;

LogEntry entry = new LogEntry
            {
                message = myMessage ,
                logType = msgLogType ,
                timeStamp = DateTime.Now
            };

And as a bonus, Visual Studio suggests the class properties when typing within the brackets!
VS Object Initializer

For reference, the MSDN Site: https://msdn.microsoft.com/en-us/library/bb397680.aspx

Robin

Software Engineer / Application Developer

Subscribe to robsCode

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!