Syntax for virtual members

Consider the following class written in C # .net 4.0 (usually in the nhibernate class):

public class CandidateEntity : EntityBase { public virtual IList<GradeEntity> Grades { get; set; } public CandidateEntity() { Grades = new List<GradeEntity>(); } } 

This line receives a valid warning "virtual member call in constructor". Where should I initialize this collection?

Hi,

+8
syntax c #
source share
4 answers

The support field is one way. Another is to use a private setter. This works well in nHibernate.

 public virtual IList<GradeEntity> Grades { get; private set; } public CandidateEntity() { Grades = new List<GradeEntity>(); } 
+11
source share

Use the support field and initialize the support field in the constructor. Alternatively, make the class airtight.

 private IList<GradeEntity> _grades public virtual IList<GradeEntity> Grades { get { return _grades; } set { _grades = value; } } public CandidatesEntity() { _grades = new List<GradeEntity>(); } 
+9
source share

If you create a sealed class, you also will not receive a warning (because a problem is only a problem if you inherit this class and redefine the member).

Edit after OP comment:

Ah, right. I usually only encounter this when dealing with inherited virtual members. Yads' answer is probably most useful to you.

Also note that you do not need to do the entire virtual property. Consider this:

 List<Grade> Grades { get { return _grades; } set { _grades = value; OnGradesChanged(); } protected virtual OnGradesChanged() { } 

Usually you do not want to store Grades differently in a derived class. You just need to do some updating when it changes. In this way, you provide additional guidance to the derived class, and you are sure that you can trust the scope of support.

PS Do you know that people can edit List<Grade> if your classes do not see it? You should use an ObservableCollection , which triggers an event when the collection changes externally. In this case, you only need to open the readonly Grades property.

0
source share

Create an overridden (virtual) OnInit method or something similar and initialize Grade there, then call OnInit from the constructor.

A warning informs you that you are creating behavior that developers will find it difficult to override.

-one
source share

Source: https://habr.com/ru/post/651415/


All Articles