Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for virtual members

Tags:

syntax

c#

Consider the following class written in c# .net 4.0 (typically found in a nhibernate class):

public class CandidateEntity : EntityBase
{
    public virtual IList<GradeEntity> Grades { get; set; }

    public CandidateEntity()
    {
         Grades = new List<GradeEntity>(); 
    }
}

This line gets a well founded warning "virtual member call in the constructor". Where shall I initialize this collection ?

Regards,

like image 882
Calin Avatar asked Jan 23 '11 19:01

Calin


People also ask

Which is the correct syntax of declaring a virtual?

Which is the correct syntax of declaring a virtual function? Explanation: To make a function virtual function we just need to add virtual keyword at the starting of the function declaration.

What is virtual function example?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

What is the syntax for a virtual function?

In other words, the member function of Base is not overridden. In order to avoid this, we declare the print() function of the Base class as virtual by using the virtual keyword. class Base { public: virtual void print() { // code } }; Virtual functions are an integral part of polymorphism in C++.

What is a virtual member in C++?

Virtual member functions are declared with the keyword virtual . They allow dynamic binding of member functions. Because all virtual functions must be member functions, virtual member functions are simply called virtual functions.


1 Answers

The backing 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>();
}
like image 85
Matt Johnson-Pint Avatar answered Oct 11 '22 02:10

Matt Johnson-Pint