The modifier virtual
serves to inform that this property can be modified by some class it inherits from this class, so it only makes sense for you to mark a property as virtual
if you plan to create some class that you inherit from it and can modify the behavior of it.
Using as an example the Entity Framework, you could possibly have something like:
public class Endereco
{
public int BairroID { get; set; }
public virtual Bairro Bairro { get; set; }
}
This is because the Entity Framework
need to create a runtime class. This class will override the property Bairro
for her to perform a query when accessed, then we would have something like:
public class Endereco_0C88CB7B3C2849FC85E80ECB5A1FAD4B : Endereco
{
private Bairro _bairro;
public override Bairro Bairro
{
get
{
if (bairro == null || bairro.BairroID != this.BairroID)
this._bairro = context.Bairros.Find(this.BairroID);
return this._bairro;
}
set
{
this._bairro = value;
this.BairroID = this._bairro!= default(Bairro) ? this._bairro.BairroID : default(int);
}
}
}
Note that the above implementation is not even close to the implementation made by the Entity Framework, it is just there to illustrate the Lazy Loading carried out by the same.
Now, on the question, which is better, I advise you to follow the recommendation given by the ORM/Framework you are using.
In the case of Nhibernate, maybe it will be interesting to have all the properties virtual
and not having the counter-party to the navigation properties, in this case you would have only the public virtual Bairro Bairro
and would not have the public virtual int BairroID
.
In Entity Framework, I would say to mark as virtual apenas
the navigation properties, and maintain the navigation property and its counter-part, so you would have both public virtual Bairro Bairro
, as public int BairroID
(the latter without the virtual
).
We are talking about Entity Framework?
– Leonel Sanches da Silva
@Gypsy omorrisonmendez yes, in this case yes.
– pnet