Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using virtual properties to support NHibernate proxies; ReSharper warns of virtual member call in constructor

I'm trying to support NHibernate proxying of my entities by marking the entities' properties as virtual:

public class Video : IAbstractDomainEntity<string>
{
    public virtual string Id { get; set; }
    public virtual string Title { get; set; }
    public virtual int Duration { get; set; }
    public virtual string Author { get; set; }
    public virtual bool HighDefinition { get; set; }

    public Video()
    {
        Id = string.Empty;
        Title = string.Empty;
        Author = string.Empty;
    }
}

ReSharper states that this is bad practice due to the issue described here: Virtual member call in a constructor

I understand the problem and I also understand that I cannot mark my class as sealed because then NHibernate would not be able to generate a proxy from the entity.

Do I just live with the waning and make sure not to do anything weird with my setters?

like image 683
Sean Anderson Avatar asked Jan 22 '26 14:01

Sean Anderson


1 Answers

The best-practice is to use properties with backing fields:

public class Video : IAbstractDomainEntity<string>
{
    private string _id;
    private string _title;
    private string _author;

    public virtual string Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public virtual string Title
    {
        get { return _title; }
        set { _title = value; }
    }
    public virtual string Author
    {
        get { return _author; }
        set { _author = value; }
    }
    public virtual int Duration { get; set; }
    public virtual bool HighDefinition { get; set; }

    public Video()
    {
        _id = string.Empty;
        _title = string.Empty;
        _author = string.Empty;
    }
}

So you can avoid problems on child classes and you don't see any warning anymore

like image 51
giammin Avatar answered Jan 25 '26 05:01

giammin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!