I was just wondering about some CodeWarning (ConstructorsShouldNotCallBaseClassVirtualMethods), and if there is a better way to do it. I have a simple log collector class, and I am using NHibernate to retrieve some of the objects.
Some times I create objects by myself (of course) and add them to NHibernate for persistance. What is the best way to make sure that Lists are never NULL.
Currently I am doing this, but it does not seems “perfect”. Any idea on this topic?
public class LogRun
{
public virtual int Id { get; private set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime EndTime { get; set; }
public virtual IList<Log> LogMessages { get; set; }
public virtual int LogMessageCount { get { return LogMessages.Count; } }
public LogRun()
{
LogMessages = new List<Log>();
}
}
Is LogMessages a persisted thing? If so, it’s best practice to never expose a public setter. NHibernate gets weird if you retreive from the database and then replace that IList with a new one:
If you note, NHibernate is returning a proxied object and replacing it with a generic list will cause it to go wonky when you try and save back.
As a rule, I prefer to have a private field that I initialize and then expose only a getter to the client:
Actually, I go a step further, the client gets an IEnumerable<> and I add a helper function for the add.
My implmentation would look like