views:

321

answers:

2

Just reading about nHibernate, why do the class properties have to be virtual? What is the reasononing behind that?

+8  A: 

I would suggest you read Must Everything Be Virtual With NHibernate?

The quick answer to that question is: because we need members to be virtual in order to do our lazy loading magic/voodoo.

The longer answer is more interesting though. An important feature that any real ORM must have is transparent Lazy Loading. If you retrieve an object through an ORM, you don’t want it to automatically pull in an entire object graph (not by default anyway), yet you don’t want to litter your code with checks to see if certain associations have been loaded yet, and then loading them if necessary. This is the ORM’s responsibility. Ideally, you want to be able to access properties and have the ORM load the necessary data upon first access of those properties if the data hasn’t been retrieved yet.

Andrew Hare
+1  A: 

As Andrew said, properties are virtual to trigger lazy loading. Here is an explanation as to why that is: At runtime NHibernate will substitute proxy objects for your real property objects. Once they are accessed, the proxy objects know how to get the real objects for you. Marking the properties as virtual allows this substitution to happen.

Daniel Auger